答:
Pro:

Isolates changes to your code if you ever have to change databases, or could provide a mechanism for supporting multiple SQL dialects, optimizations, or databases with the same Java code as @Morons said

SQL-only changes can be made after deployment.

Separation of programmer duties and DBA duties as @JVXR said.

A really talented and hardworking DBA should be able to write SQL and manually load database fields into Java objects with better performance (faster run-time) than an ORM tool.  The same was said of compilers vs. assembly language for years, and you don't see us writing much assembly any more.  Where it matters, this is a pro, but I would say it does not often matter.

Con:

How do you meaningfully manage your database sessions if you've hidden the way your code interacts with the database in a separate non-Java file?  Seems it would make this more difficult.

The point of ORM (Object-Relational-Mapping) tools like Hibernate is to let you work with Java objects and query abstractions and let the ORM tool do the queries for you.  Querying a table and loading each column into the proper field of your Java object is a lot of programming work.  Maintaining that code is lots of work too.  ORM tools do nice things like provide proxy objects that eliminate unnecessary queries, while letting you work with database data as type-safe Java objects - without you writing any of the code to do that.  If you then start writing lots of manual SQL queries, you are defeating the purpose of ORM.  Some SQL almost always ends up being written and that could go in an external (non-Java) file.  But usually the less, the better.  It's a question of what you want to spend your time on.  If you use hardly any SQL, it doesn't matter so much where you put it.

In most applications, the "real work" is carried out in the database queries and updates and the code closest to those queries and updates.  Hiding those queries in another file seems to obscure it - encouraging the programmer to be ignorant of the database.  That could be good division of labor, or even a useful abstraction (such as what ORM tools provide) or it could be an unnecessary hurdle to understanding.  Good naming of the SQL routines could mitigate this issue somewhat.

Increased separation of Java and Database code could be a barrier to refactoring.  Instead of searching for the field, you need to find the queries that use it, then find where each query is used.  An extra step.

Thoughts

I've been moving in the opposite direction - I generate my ORM Java objects from the database after every database change and I have it also generate SQL and HQL (Hibernate Query Language) tokens for each column and each table.  In every SQL query or HQL symbolic query, I append the token instead of the field name.  This way I can search for where each field is used in the application, either as a Java object field, in a HQL query, or in a SQL query.

Here is a typesafe Hibernate-style Criteria query example, querying un-deleted records from the "thing" table from a single company that have an owner:

In Thing.java:

```<code>// SQL Table name
public static final String SQL_thing = "thing";
// SQL Column names
public static final String SQL_id = "id";
public static final String SQL_company_id = "company_id";
public static final String SQL_owner_id = "owner_id";
public static final String SQL_is_deleted = "is_deleted";

// HQL object name
public static final String HQL_Thing = "Thing";
// HQL field names
public static final String HQL_id = "id";
public static final String HQL_company = "company";
public static final String HQL_owner = "owner";
public static final String HQL_isDeleted = "isDeleted";
</code>```

In-Java SQL Example

If I had to drop down to SQL, e.g. to query thing IDs, it would look like the following.  Please note that since symbol is a final String, the concatenation is done by the compiler, not at runtime, even in Java, even with the + operator:

```<code>jdbcConn = HibernateUtil.getJdbcConnection();

String query = "select " + Thing.SQL_id +
               " from " + Thing.SQL_thing +
               " where " + Thing.SQL_company_id +
               " = ? and " + Thing.SQL_is_deleted +
               " = b'0' and " + Thing.SQL_owner_id +
               " is not null";

PreparedStatement stmt = jdbcConn.prepareStatement(query);
stmt.setLong(1, someCompany.getId());

ResultSet results = stmt.executeQuery();

while (results.next()) {
    Long thingId = results.getLong(1));
    // do stuff with things IDs
}
</code>```

Obviously, I try not to drop to SQL, unless I absolutely need to for performance reasons, or to do something like running a SQL report.

Criteria Query Example

In a code which builds data for a screen of the application:

```<code>Crit<Thing> tCrit = Crit.create(Thing.class);
tCrit.add(Restrictions.eq(Thing.HQL_company, someCompany));
tCrit.add(Restrictions.eq(Thing.HQL_isDeleted, false));
tCrit.add(Restrictions.isNotNull(Thing.HQL_owner));

for (Thing t : tCrit.list()) {
    // do stuff with things
}
</code>```

I somewhat try not to use criteria, except for performance.  Again, I want to stay in Java-land as much as possible.

Pure-Java ORM Example

```<code>for (Thing t : someCompany.getThings()) {
    if ( t.getIsDeleted() ||
         (t.getOwner() == null) ) {
        continue;
    }
    // do stuff with things
}
</code>```

Clearly we are bringing back extra records (some ownerless and deleted Things), but if there are many Things and most are not deleted and have owners, the performance hit will be minimal.

External SQL Example

For reference, here is what an external-SQL implementation might look like.  External SQL file (WEB4J-like syntax):

```<code>NON_DELETED_THINGS_WITH_OWNERS {
select t.id, t.company_id, t.owner_id, t.is_deleted
from thing where t.company_id = ? and
    t.is_deleted = b'0' and
    t.owner_id is not null; }
</code>```

I'm not showing or think much about how the external SQL file query gets made available to Java.  Presumably a tool like WEB4J would take care of that, but you need to specify the SQL file or files somehow and your tool makes those queries available, I'm imagining as a String in this example, but it could be a prepared statement or some other abstraction.

Company Query Method:

```<code>public Set<Thing> getNonDeletedThingsWithOwners(Connection jdbcConn) {

    PreparedStatement stmt = jdbcConn.prepareStatement(NON_DELETED_THINGS_WITH_OWNERS);
    stmt.setLong(1, this.id);

    ResultSet results = stmt.executeQuery();

    Set<Thing> things = new HashSet<>();
    while (results.next()) {
        things.add(Thing.valueOf(results));
    }
    return things;
}
</code>```

Thing Factory Method:

```<code>public static Thing valueOf(ResultSet rs) throws SQLException {
    Thing t = new Thing();
    t.id = rs.getLong(SQL_id);
    t.company_id = rs.getLong(SQL_company_id);
    t.owner_id = rs.getLong(SQL_owner_id);
    t.isDeleted = rs.getBoolean(SQL_is_deleted);
    return t;
}
</code>```

Usage:

```<code>Set<Thing> thingSet = someCompany.getNonDeletedThingsWithOwners();

for (Thing t : thingSet) {
    // do stuff with things
}
</code>```

Compare this to the Pure-Java ORM Example or the Criteria Query Example - this is a ton of code, spread across four files!  If you need the performance and the control, then invest the energy.  But when ORM can save me from this, I think I'll let it.

Debugging

I assume here that you have a tool that reliably generates your Java database objects for you.

With the Pure-Java example, there is no debugging of SQL or queries unless performance is an issue.  You could still perform the wrong tests (e.g. forget to exclude ownerless things), but it's pretty straight-forward - keeps you focused on what you are doing, thus minimizing this possiblity.  You can ask your ORM to spit out the actual queries in your log file if you need to tune them or see that you query the thing table 100 separate times or something like that, but this code results in a single query.

It's possible to pass the wrong type of object or nulls to the Criteria query.  Also, since it's wordy, it takes longer to see what you are actually doing and bugs are easier to creep into your criteria.

With In-Java SQL, you have all the issues above, plus getting the SQL syntax right.  I admit my symbols make this a little more complicated, but I feel the refactoring plus is bigger than the readability minus.

With the External SQL example, you have all of the error possibilities mentioned above, plus all the extra code from loading the results into the object.  Plus the multiple files that can get out of synch.  What if you rename, delete, or add a field - will you get a compilation error?  Will you find all the places you need to change?  Or do you have to find it in testing.

I'd have to say that from a debugging point of view, ORM with pure Java is a clear win, with additional debugging every step you move away from there.

Conclusion

Using ORM and symbols has saved me countless hours of refactoring difficulties and lets me make database changes with ease because when something breaks, it won't compile.  When code gets big, refactoring is the only way to manage complexity, and it gets harder as it gets bigger, so above a certain size of code base, ease of refactoring becomes a primary goal.

ORM also eliminates opportunities for bugs and the performance cost for this is usually minimal.  You can still drop-down to SQL as necessary, but I think having less SQL in your application is a better goal than putting SQL in separate files.

Title: Externalising SQL Queries in Java

Body:
Pro:

Isolates changes to your code if you ever have to change databases, or could provide a mechanism for supporting multiple SQL dialects, optimizations, or databases with the same Java code as @Morons said

SQL-only changes can be made after deployment.

Separation of programmer duties and DBA duties as @JVXR said.

A really talented and hardworking DBA should be able to write SQL and manually load database fields into Java objects with better performance (faster run-time) than an ORM tool.  The same was said of compilers vs. assembly language for years, and you don't see us writing much assembly any more.  Where it matters, this is a pro, but I would say it does not often matter.

Con:

How do you meaningfully manage your database sessions if you've hidden the way your code interacts with the database in a separate non-Java file?  Seems it would make this more difficult.

The point of ORM (Object-Relational-Mapping) tools like Hibernate is to let you work with Java objects and query abstractions and let the ORM tool do the queries for you.  Querying a table and loading each column into the proper field of your Java object is a lot of programming work.  Maintaining that code is lots of work too.  ORM tools do nice things like provide proxy objects that eliminate unnecessary queries, while letting you work with database data as type-safe Java objects - without you writing any of the code to do that.  If you then start writing lots of manual SQL queries, you are defeating the purpose of ORM.  Some SQL almost always ends up being written and that could go in an external (non-Java) file.  But usually the less, the better.  It's a question of what you want to spend your time on.  If you use hardly any SQL, it doesn't matter so much where you put it.

In most applications, the "real work" is carried out in the database queries and updates and the code closest to those queries and updates.  Hiding those queries in another file seems to obscure it - encouraging the programmer to be ignorant of the database.  That could be good division of labor, or even a useful abstraction (such as what ORM tools provide) or it could be an unnecessary hurdle to understanding.  Good naming of the SQL routines could mitigate this issue somewhat.

Increased separation of Java and Database code could be a barrier to refactoring.  Instead of searching for the field, you need to find the queries that use it, then find where each query is used.  An extra step.

Thoughts

I've been moving in the opposite direction - I generate my ORM Java objects from the database after every database change and I have it also generate SQL and HQL (Hibernate Query Language) tokens for each column and each table.  In every SQL query or HQL symbolic query, I append the token instead of the field name.  This way I can search for where each field is used in the application, either as a Java object field, in a HQL query, or in a SQL query.

Here is a typesafe Hibernate-style Criteria query example, querying un-deleted records from the "thing" table from a single company that have an owner:

In Thing.java:

// SQL Table name
public static final String SQL_thing = "thing";
// SQL Column names
public static final String SQL_id = "id";
public static final String SQL_company_id = "company_id";
public static final String SQL_owner_id = "owner_id";
public static final String SQL_is_deleted = "is_deleted";

// HQL object name
public static final String HQL_Thing = "Thing";
// HQL field names
public static final String HQL_id = "id";
public static final String HQL_company = "company";
public static final String HQL_owner = "owner";
public static final String HQL_isDeleted = "isDeleted";

In-Java SQL Example

If I had to drop down to SQL, e.g. to query thing IDs, it would look like the following.  Please note that since symbol is a final String, the concatenation is done by the compiler, not at runtime, even in Java, even with the + operator:

jdbcConn = HibernateUtil.getJdbcConnection();

String query = "select " + Thing.SQL_id +
               " from " + Thing.SQL_thing +
               " where " + Thing.SQL_company_id +
               " = ? and " + Thing.SQL_is_deleted +
               " = b'0' and " + Thing.SQL_owner_id +
               " is not null";

PreparedStatement stmt = jdbcConn.prepareStatement(query);
stmt.setLong(1, someCompany.getId());

ResultSet results = stmt.executeQuery();

while (results.next()) {
    Long thingId = results.getLong(1));
    // do stuff with things IDs
}

Obviously, I try not to drop to SQL, unless I absolutely need to for performance reasons, or to do something like running a SQL report.

Criteria Query Example

In a code which builds data for a screen of the application:

Crit<Thing> tCrit = Crit.create(Thing.class);
tCrit.add(Restrictions.eq(Thing.HQL_company, someCompany));
tCrit.add(Restrictions.eq(Thing.HQL_isDeleted, false));
tCrit.add(Restrictions.isNotNull(Thing.HQL_owner));

for (Thing t : tCrit.list()) {
    // do stuff with things
}

I somewhat try not to use criteria, except for performance.  Again, I want to stay in Java-land as much as possible.

Pure-Java ORM Example

for (Thing t : someCompany.getThings()) {
    if ( t.getIsDeleted() ||
         (t.getOwner() == null) ) {
        continue;
    }
    // do stuff with things
}

Clearly we are bringing back extra records (some ownerless and deleted Things), but if there are many Things and most are not deleted and have owners, the performance hit will be minimal.

External SQL Example

For reference, here is what an external-SQL implementation might look like.  External SQL file (WEB4J-like syntax):

NON_DELETED_THINGS_WITH_OWNERS {
select t.id, t.company_id, t.owner_id, t.is_deleted
from thing where t.company_id = ? and
    t.is_deleted = b'0' and
    t.owner_id is not null; }

I'm not showing or think much about how the external SQL file query gets made available to Java.  Presumably a tool like WEB4J would take care of that, but you need to specify the SQL file or files somehow and your tool makes those queries available, I'm imagining as a String in this example, but it could be a prepared statement or some other abstraction.

Company Query Method:

public Set<Thing> getNonDeletedThingsWithOwners(Connection jdbcConn) {

    PreparedStatement stmt = jdbcConn.prepareStatement(NON_DELETED_THINGS_WITH_OWNERS);
    stmt.setLong(1, this.id);

    ResultSet results = stmt.executeQuery();

    Set<Thing> things = new HashSet<>();
    while (results.next()) {
        things.add(Thing.valueOf(results));
    }
    return things;
}

Thing Factory Method:

public static Thing valueOf(ResultSet rs) throws SQLException {
    Thing t = new Thing();
    t.id = rs.getLong(SQL_id);
    t.company_id = rs.getLong(SQL_company_id);
    t.owner_id = rs.getLong(SQL_owner_id);
    t.isDeleted = rs.getBoolean(SQL_is_deleted);
    return t;
}

Usage:

Set<Thing> thingSet = someCompany.getNonDeletedThingsWithOwners();

for (Thing t : thingSet) {
    // do stuff with things
}

Compare this to the Pure-Java ORM Example or the Criteria Query Example - this is a ton of code, spread across four files!  If you need the performance and the control, then invest the energy.  But when ORM can save me from this, I think I'll let it.

Debugging

I assume here that you have a tool that reliably generates your Java database objects for you.

With the Pure-Java example, there is no debugging of SQL or queries unless performance is an issue.  You could still perform the wrong tests (e.g. forget to exclude ownerless things), but it's pretty straight-forward - keeps you focused on what you are doing, thus minimizing this possiblity.  You can ask your ORM to spit out the actual queries in your log file if you need to tune them or see that you query the thing table 100 separate times or something like that, but this code results in a single query.

It's possible to pass the wrong type of object or nulls to the Criteria query.  Also, since it's wordy, it takes longer to see what you are actually doing and bugs are easier to creep into your criteria.

With In-Java SQL, you have all the issues above, plus getting the SQL syntax right.  I admit my symbols make this a little more complicated, but I feel the refactoring plus is bigger than the readability minus.

With the External SQL example, you have all of the error possibilities mentioned above, plus all the extra code from loading the results into the object.  Plus the multiple files that can get out of synch.  What if you rename, delete, or add a field - will you get a compilation error?  Will you find all the places you need to change?  Or do you have to find it in testing.

I'd have to say that from a debugging point of view, ORM with pure Java is a clear win, with additional debugging every step you move away from there.

Conclusion

Using ORM and symbols has saved me countless hours of refactoring difficulties and lets me make database changes with ease because when something breaks, it won't compile.  When code gets big, refactoring is the only way to manage complexity, and it gets harder as it gets bigger, so above a certain size of code base, ease of refactoring becomes a primary goal.

ORM also eliminates opportunities for bugs and the performance cost for this is usually minimal.  You can still drop-down to SQL as necessary, but I think having less SQL in your application is a better goal than putting SQL in separate files.


问:
Externalising SQL Queries in Java
What are the advantages and disadvantages of externalising SQL queries in Java (or similar general-purpose object-oriented programming language.  Externalizing means storing all SQL in a separate non-java file or files.  Several good examples are here.

Does it make debugging harder or easier?

答:
Pros:

--It will be easier for the DB person to touch the sql.

--No rebuild needed when sql changes (assuming interfaces are the same)

Cons:

--negation of the pros above

--It can be convenient to see the fields in the sql next to the code that is utilizing that sql.

OwnerDisplayName: shamis

ContentLicense: CC BY-SA 3.0

Title: Externalising SQL Queries in Java


问:
How to avoid general names for abstract classes?
In general it's good to avoid words like "handle" or "process" as part of routine names and class names, unless you are dealing with (e.g.) file handles or (e.g.) unix processes.  However abstract classes often don't really know what they're going to do with something besides, say, process it.  In my current situation I have an "EmailProcessor" that logs into a user's inbox and processes messages from it.  It's not really clear to me how to give this a more precise name, although I've noticed the following style matter arises:

better to treat derived classes as clients and named the base class by the part of the functionality it implements?  Gives it more meaning but will violate is-a.  E.g. EmailAcquirer would be a reasonable name since it's acquiring for the derived class, but the derived class won't be acquiring for anyone.

Or just really vague name since who knows what the derived classes will do.  However "Processor" is still too general since it's doing many relevant operations, like logging in and using IMAP.

Any way out of this dilemma?

Problem is more evident for abstract methods, in which you can't really answer the question "what does this do?" because the answer is simply "whatever the client wants."

答: Think about why it's bad to use such words. Are they descriptive? What words are there to describe the classes? EmailBaseClass? Could that be more descriptive than say EmailManager or something similar? The key is to have an insight about the class in question, so find proper verbs or nouns. Treat your code like it was poetry.


问:
Do programmers possess the means of production?
I was listening to The Servile State by Hilare Belloc this morning and pondering whether or not I possessed the means of production, as did the peasant of the Middle Ages; as did not his descendants after the oligarchs of England forced him into servitude.

The means of production was the arable land that the serf was seated on, which, even though not legally his, was illegal to evict him from.

So, as programmers, with the hitherto unknown supply of free tools and resources, have we reclaimed as a class of workers, unlike any others, the means of production? Given the chance, a midrange PC and a stable internet connection, could we not each of us be wholly self-sufficient and not just wage-earners?

答:
Realistically, to posses the means of production you need to be able to produce something using only equipment you own, and turn that product into cash.  So, farmers dependent on a railroad monopoly to actually sell their crops don't really own the means of production.

The barrier to entry of producing a computer program is still relatively low.  Actually getting cash for that program requires a lot more capital unless you are targeting niche markets.  The top programs that earn the lion's share of money usually are harder to even produce, and getting big money out of them usually needs a lot of marketing.  The internet has helped make hitting it big easier, but patent law has added a lot to the expense.

So, programmers do posses the means of production at the less profitable low end of the market, but at the high end the means of production include marketing departments and huge teams of lawyers, and programmers don't have those.


答:
The problem is not the name, but that you are putting too much in one class.

In your example class, some parts are very concrete (how the mails will be obtained). Other parts are very abstract (what you will do with the mails).

Better to do this with seperate classes, than with inheritance.

I suggest:

an abstract MessageIterator, subclassed by a POPMailBoxDownloader

another class that OWNS a POPMailBoxDownloader and does something with the messages.

Title: How to avoid general names for abstract classes?

Body:
In general it's good to avoid words like "handle" or "process" as part of routine names and class names, unless you are dealing with (e.g.) file handles or (e.g.) unix processes.  However abstract classes often don't really know what they're going to do with something besides, say, process it.  In my current situation I have an "EmailProcessor" that logs into a user's inbox and processes messages from it.  It's not really clear to me how to give this a more precise name, although I've noticed the following style matter arises:

better to treat derived classes as clients and named the base class by the part of the functionality it implements?  Gives it more meaning but will violate is-a.  E.g. EmailAcquirer would be a reasonable name since it's acquiring for the derived class, but the derived class won't be acquiring for anyone.

Or just really vague name since who knows what the derived classes will do.  However "Processor" is still too general since it's doing many relevant operations, like logging in and using IMAP.

Any way out of this dilemma?

Problem is more evident for abstract methods, in which you can't really answer the question "what does this do?" because the answer is simply "whatever the client wants."


答:
If I cannot find a good name for a class I write an inline code documentation for the class. It describes the purpose of the class in one scentence. Usually I can derive a good name for the class from this description. This is also helpful for abstract classes.

If the description of class is "Logs into a user's inbox and processes messages from it", I would suggest "InboxProcessor" as a class name. If a derivative class has "Logs into a user's inbox and moves spam email to a spam folder" as description, I would choose "InboxSpamMover" as a name.

I do not see a problem when using generic names like "processor" if it reflects the generic purpose of an abstract class.

If you have problems with describing the purpose of a class in one or two scentences, then you might have a design problem. Maybe the class is doing too much and violates the Single Responsibility Principle. This also applies to abstract classes.


答:
I think it is true that programmers (can) possess their means of production because, as pointed out by others, computers and basic software tools that we need to produce software come at an affordable price.
Besides that, distributing software through the internet or by burning CD's / DVD's is also relatively cheap.

However, up to now independent programmers have only been successful in the following areas:

Relatively small, niche products (tools, phone applications, and so on) that can be conceived, developed and maintained by an individual developer (or a relatively small team).

Open source projects in which many programmers joined to produce something for themselves (i.e. general-purpose software like operating systems, web servers, compilers, web browsers, etc): they gave away their labor in order to have some software they could use in return. Of course, this could only be an extra activity besides their normal job in which they had to earn a living.

On the other hand, no (or at least very few) open source projects or independent developer teams have managed to produce large, sophisticated software for a particular class of customers (say, a flight booking system). Why? Because this requires the coordinated work of many programmers (and analysts, testers, and so on) to produce something that they will never use themselves. I guess this would require independent developers to organize themselves in cooperatives (developer-owned companies).

So it is not sufficient to own the means of production and have labor power: independent programmers have not managed to organize themselves in such a way that they can compete with the traditional software industry run through capital investment, and therefore many (most) programmers still have to work as wage earners.

Just my 2 cents.

Title: Do programmers possess the means of production?

Body:
I was listening to The Servile State by Hilare Belloc this morning and pondering whether or not I possessed the means of production, as did the peasant of the Middle Ages; as did not his descendants after the oligarchs of England forced him into servitude.

The means of production was the arable land that the serf was seated on, which, even though not legally his, was illegal to evict him from.

So, as programmers, with the hitherto unknown supply of free tools and resources, have we reclaimed as a class of workers, unlike any others, the means of production? Given the chance, a midrange PC and a stable internet connection, could we not each of us be wholly self-sufficient and not just wage-earners?


问:
Compiling OpenGL Assembly Language (ARB) assembly code
I have two questions to ask.

If I want to code in ARB, what are the prerequisites I need to write the code?

I have been using OpenGL and DirectX lately. I want to compile and run the ARB code. What compiler should I use to compile and run the code?

答:
It's no longer advised to code directly to assembly. It was important during Nvidia FX5xxx/Radeon 9700 era. A very long time ago. Now all shaders are compiled by drivers to extract max performance out of the platform.

Use OpenGL shading language, or use Nvidia Cg to generate an assembly from C++ like code.


答:
To paraphrase Frank Zappa, it are what it is and should be named that way.  Your example just doesn't dig deep enough into what kind of processing is going on.  Is it an EmailToTroubleTicketProcessor, an EmailGrammarCorrector or an EmailSpamDetector?

Problem is more evident for abstract methods, in which you can't
  really answer the question "what does this do?" because the answer is
  simply "whatever the client wants."

That's not exactly true; the question you can't answer for something abstract is "how does it do what it does?" because that's implementation-specific.  If an EmailSender class has a DeliveryStatus deliver(Email e) method, there's an implied contract that an implementation will take an email, try to deliver it and return some status about how it went.  You don't care whether it connects to a SMTP server or prints it out to be strapped to a homing pigeon as long as the implementation does what was promised.  Abstracts just quantify that promise so an implementation can say, "yeah, I do that."


答:
Having queries as stored procedures in the database is preferable because:

1> They are pre-compiled, hence will probably run faster.

2> You can update them independent of the code base. It is usually easier to run a sql script than it is to reinstall an application, particularly in a managed corporate style environment.

3> Easier to debug/test/performance tune - you can run the query easily free of the application.

4> Allows the database structure to be changed without needing to update the application.

5> Allows implementation on different database engines with one code base for the application, with the negative of multiple code bases for each DB. The syntax used for different db's tends to be different enough that some tweaking will be needed unless you use the simplest of SQL (particularly with stored procedures).

The main con I can see is that the sql is not hidden in the compiled code, so is easier for an external party to read and reverse engineer the application which may or may not be important for a commercial application.

Title: Externalising SQL Queries in Java

Body:
What are the advantages and disadvantages of externalising SQL queries in Java (or similar general-purpose object-oriented programming language.  Externalizing means storing all SQL in a separate non-java file or files.  Several good examples are here.

Does it make debugging harder or easier?


问:
Is it a good practice to have Epics under User Stories?
In my current team there is a practice of putting Epics under User Stories and sometimes even User Stories or Epics under Tasks! When questioned, the usual reply is: "if it is not a good practice then the project management tool would not have allowed doing so!" (IBM Rational Team Concert, for one does not prevent such practice.)

What do the experts here think about this?

答:
Epic is not a special artifact. It is a user story (or product backlog item) violating some basic characteristics of common user stories:

It is usually a big story with a lot of hidden details

It usually contains a lot of uncertainty because of hidden details

It is usually very hard to estimate such story (sometimes even impossible) again because of size and uncertainty

It is usually not possible to fit a discussion about story details or acceptance criteria into some used time box because there is simply too many of them (one Epic story can take more time for discussion then whole planning meeting - once you have suspicion that this is going to happen you should immediately exclude such story from planning)

Even if your estimation counts with uncertainty you very often ends with the estimate which doesn't fit into iteration length

But even with these characteristics it is still a user story and it belongs to product backlog. The story can become an epic by two ways:

Product owner declares it as epic - It is usually some high level feature noted for future investigation or discussion.

Team declares it as epic - It means that team doesn't understand the story because it is too high level for estimation. The story must be divided before team can proceed with this story.

What you may find the most important is that in both scenarios the epic user story is work for product owner - not for the team. The product owner must take the epic and split it into more specific stories resolving all bad characteristics of the big one - it may be even iterative process (there may be even more high level backlog item called Theme). Product owner is responsible for maintaining product backlog - no one else.

In my current team there is a practice of putting Epics under User
  Stories and sometimes even User Stories or Epics under Tasks!

You can sometimes consider user story as a task. It depends on granularity of tasks you want to achieve. If you for example use 1/2, 1 and 2 days tasks you can easily find that some user stories fit into such metric. But epics should obviously not fit even to 5 days tasks (unless you have one week iterations).

There are three explanations to your core problem:

Those user stories are not epics - this may be the simplest explanation. If the team handles those stories without problems, with correct involvement of product owner, with all acceptance criteria passed and within single iteration they are most probably not epics. They could be in the past but as the team builds application the knowledge about the domain grows as well as already implemented code. The real complexity of these user stories may be already different as well as the estimation. In such case it is time to schedule a new estimation session and re-estimate all previously estimated stories (team should still use the same size for story point as in the initial estimation!)

Those user stories are not epics but the team insists they are - this is skill or confidence problem. One reason may be that the team is not skilled enough (with a methodology or tool they have to use) and they are not confident with their estimates so they may put some spare time into some stories. If this is a problem of overestimating you must find a reason why is it happening but the global overestimating in general should be eliminated by correctly using velocity from previous iterations for next iteration planning.

Those user stories are epics but teams somehow magically manages to complete them. That should be a big warning. If the story was considered big without detailed information you may end with incomplete feature - even worse with feature where the team decided how to quickly implement it instead of discussing it with product owner - the whole implementation can be waste because the feature was not understood correctly. This is mainly responsibility of product owner to stop this. If you have weak product owner you must make your best to stop it yourselves because this may end by a big failure of the project.

if it is not a good practice then the project management tool would
  not have allowed doing so!

So you must show them that current practice is wrong. How long is a task containing the whole story or even epic? What team members say about work they did yesterday on daily meetings? If they says that they did something it means that they completed some task they were lazy to create. If they don't say that they did something for two days how do you know that they are not stuck and don't need help? How do you know that they are actually doing something?

And even worse: How do you track an iteration progress? Do you have a sprint burn down chart? What does it show? If you have epic user story as a task how long does it take to complete? I like to use two sprint burn down charts: one for tasks and second for stories. The first one is more internal progress tracking tool whereas the second one is the real iteration progress (at the end of the sprint only completed stories matters) but in both cases you can change the chart only if the task or story is complete - you never make changes just because you worked on a story two days but five still remain to complete it. You will extract 7 days only when the story is done because only in such case you measure your progress of work completion.

Extracting days or hours based on incomplete work is like tracking how many mandays your team spent on the project since iteration started. That has nothing to do with progress tracking - you don't need to know that team worked on features 122,5 hours this week. You need to know how was that 122,5 hours used to complete work. If you don't see how tasks or stories where completed during those 122,5 hours you are doing it wrong - in the worst case you can end with 122,5 hours spent and none completed task or story. Even if everything goes right you may end in situation where you have 10 stories planned for an iteration and at the end of the iteration you need 10 more hours to complete planned stories - 1 hour for each. How do you think my burn down chart would look like in such case? Yes, horizontal line since a day one to the end of the iteration = no work done because that is exactly result of such sprint.

IBM Rational Team Concert, for one does not prevent such practice.

I have never used that product so my judgement may not relate to that concrete product but I learned one thing about enterprise software (IBM makes enterprise software). Most (but not all) of enterprise software products are created to amaze people responsible for purchasing enterprise products, not to amaze people who will have to use those products. It is important to have tool solving some enterprise problem in "enterprise" way.

The greatest agile management tools come from smaller agile companies where agile is really used and it is not bent to fit enterprise bureaucracy. I would not be surprised if agile management tools provided by enterprises had been created by teams not using agile and even people who never used agile before. Agile is a trend and every big company providing enterprise software must have its own tool - at all costs.


问:
Should a programmer take writing lessons to enhance code expressiveness?
Given that programmers are authors and write code to express abstract thoughts and concepts, and good code should be read by other programmers without difficulties and misunderstandings, should a programmer take writing lessons to write better code?

Abstracting concepts and real world problems/entities is an important part of writing good code, and a good mastery of the language used for coding should allow the programmer to express his thoughts more easily, or in a better way. Besides, when trying to write or rewrite some code to make it better, much time can be spent in deciding the names for functions, variables or data structures.

I think this could also help to avoid writing code with more than one meaning, often cause of misunderstanding between different programmers. Code should always express clearly its function unambiguously.

答:
My code increasingly depends on creating a shared vocabulary between the business and the technical teams. I'd say that improving your writing skills can help you reduce ambiguity and misunderstandings in these efforts, but that it's not likely to help the expressiveness of your code.

The literary notion of expressiveness is not the same as the programming notion of expressiveness. In many cases, ambiguity in language can be used as a literary device, even in non-fiction, in a form that increases expressiveness, because it will trigger various cultural, linguistic and symbolic associations in the reader, both intended and unintended. This kind of expressiveness is not desirable in programming; abstraction is more valuable than ambiguity. In programming, abstraction increases flexibility with perhaps some cost of cognitive load. Abstraction in literary form can have the opposite of the effect it has in programming: the more abstract your writing, the more likely the reader will have the perception that you are saying nothing. All those symbols and associations that result from concrete speech have value, because they resonate with your readers more directly than abstractions.

However, a programmer is not a machine. Humans benefit in often unexpected ways from intellectual and emotional growth. Improving your writing may result in greater customer empathy because you force yourself to struggle with communication challenges; perhaps you'll feel for that customer who says what they want, then you deliver it and they realize it's not what they need. Perhaps you'll just learn to focus on what's left unsaid.

Maybe learning to throw clay on a pottery wheel will help you start to see parallels between craftsmanship and software development. Studying the way building architects communicate might lead you to have a stronger appreciation for building a vocabulary of design patterns in programming. Studying biology might lead you to fascinating insights about how ants and bees find and communicate about food sources and how those simple mechanisms could be translated into pathfinding algorithms.

Learning things outside of your core domain are worthwhile because curious people make better developers than people who aren't.

For what it's worth, I was nearly a literature major; I ended up switching to East Asian Studies because I was more interested in the classes I was taking in that department. There's a chance I might not be in the industry had I not studied East Asian Studies, because the side effect of studying Japanese made me more valuable at the time, when a software company hired me in part due to language skills. I still had to build a deeper portfolio of technical skills, but the unintended side effects of learning anything can make you a better, more relevant software professional.


问:
Questions to ask before someone leaves
Apart from the obvious questions relating to specific project work someone is working on are there any questions I should be asking a fellow dev who is leaving the company?

So far I am thinking about;

Locations of things on the server he uses that not maybe everyone does.

Credentials he has set up that we wouldn't have needed.

Client details he has not yet saved into our CRM system.

答: If he quit by himself (i.e. wasn't laid off/fired), then ask why he quit. That may help keeping others in the future, especially if several people end up quitting for the same reasons.

Title: Questions to ask before someone leaves

ContentLicense: CC BY-SA 2.5


问:
Resources on learning to program in machine code?
I'm a student, fresh into programming and loving it, from Java to C++ and down to C. I moved backwards to the barebones and thought to go further down to Assembly.

But, to my surprise, a lot of people said it's not as fast as C and there is no use. They suggested learning either how to program a kernel or writing a C compiler. My dream is to learn to program in binary (machine code) or maybe program bare metal (program micro-controller physically) or write bios or boot loaders or something of that nature.

The only possible thing I heard after so much research is that a hex editor is the closest thing to machine language I could find in this age and era. Are there other things I'm unaware of? Are there any resources to learn to program in machine code? Preferably on a 8-bit micro-controller/microprocessor.

This question is similar to mine, but I'm interested in practical learning first and then understanding the theory.

答:
For machine language study and programming

MASM software may be used.

For MASM, the following link may be used.

http://en.wikipedia.org/wiki/Microsoft_Macro_Assembler

http://www.microsoft.com/en-us/download/details.aspx?id=12654


问:
Approach on Software Development Architecture
I am planning to standardize our way of creating project for our new projects.

Currently we are using 3tier architecture where we have our ClassLibrary Project where it includes our Data Access Layer and Business Layer

Something like:

```<code>   Solution ClassLibrary
     >ClassLibrary Project :
          >DAL(folder)
               > DAL Classes
          >BAL(folder)
               > BAL Classes
</code>```

And this Class Library dll was reference on our presentation Layer Project which are the Application(web/desktop)

Something like:

```<code>     Solution WebUniversitySystem
     >Libraries(folder)
          > ClassLibrary.dll
     >WebUniversitySystem(Project):
          >Reference ClassLibrary.dll
          >Pages etc...
</code>```

Now i am planning to do is something like:

```<code> Solution WebUniversitySystem
     >DataAccess(Project)
     >BusinesLayer(Project)
          >Reference DAL
     >WebUniversitySystem(Project):
          >Reference BAL
          >Pages etc...
</code>```

Is this OK? Or there is a good approach that we can follow?

答:
That's a pretty good approach. You've separated the concerns into projects and referenced the projects where they are used. That's good.

Since you've tagged this Visual Studio, I'm going to share how I structure my .NET software projects.

Typically I'll have these three projects, each contained within a single Visual Studio solution (.sln):

```<code>PointOfSale
|
|--PointOfSale.Domain (*A class library project. Typically Entity Framework models etc.*)
|
|--PointOfSale.WebUI  (*The UI project. Could be MVC3, or WPF, or whatever. Presentation.*)
|
|--PointOfSale.Tests  (*The unit testing project. I place all my tests in here.*)
</code>```

As far as references between the projects, the .Domain project is referenced in  both the UI project and Tests project.

Body:
That's a pretty good approach. You've separated the concerns into projects and referenced the projects where they are used. That's good.

Since you've tagged this Visual Studio, I'm going to share how I structure my .NET software projects.

Typically I'll have these three projects, each contained within a single Visual Studio solution (.sln):

PointOfSale
|
|--PointOfSale.Domain (*A class library project. Typically Entity Framework models etc.*)
|
|--PointOfSale.WebUI  (*The UI project. Could be MVC3, or WPF, or whatever. Presentation.*)
|
|--PointOfSale.Tests  (*The unit testing project. I place all my tests in here.*)

As far as references between the projects, the .Domain project is referenced in  both the UI project and Tests project.


答:
My main critique of your approach would be, don't make your BL directly depend on your DAL, put a layer of indirection in their where the BL receives the DAL via IOC or IPC (which is basically a form of IOC) Then the consumers of your BL get to choose what DAL it gets; If the consumer's a unit test it gives a mock DAL, if the consumer is that one annoying client for some reason they use a CSV DAL you hate maintaining, but for most consumers the BL is given a large DAL for enterprise use and about 20% of implemented consumers are the mobile versions presentation layer which gives the BL that in-memory DAL.

I'm a personal fan of having a shared block of data models, 2 BL's, one DAL, and a presentation layer in the MVC pattern.

Why 2 BL's? There is always a body of logic that lives at the DAL layer for actually translating the requested data into a data model, and even more complexity on the other way around, especially if you have any form of caching whatsoever. Usually people embed all of this into their DAL but end up paying a maintenance penalty they wouldn't have to if they made a separate layer above the DAL which receives DAL components in IOC and completes said logic.

The other BL then should in my opinion be idempotent in a functional paradigm with minimal if any side effects, side effects are what the dal is for.

So the dependency graph would be (layer: things it depends on):

```<code>DataModels: nothing
DAL: nothing
DALInterfaces: nothing
DALBL: DALInterfaces, DataModels
DALBLInterfaces: DALInterfaces, DataModels
BL: DataModels
BLInterfaces: DataModels
Presentation: DataModels, *Interfaces, some IOC framework or service client framework that turns the interfaces into concrete implementations.
</code>```

Then the use is such that in your presentation you would do things like:

```<code>public MenuOption[] GetMenuOptions(string username, string password)
{
    DataModels.User currentUser = _securityBl.GetUserFromThread(Thread.CurrentThread);
    // remember no side effects in BL layer, just works from inputs, so needs be told the thread
    return _usersDalBl.GetMenuOptionsForUser(currentUser);
    // this dalBl was given a concrete Dal at construction, again
    // no *direct* side effects, only the dal it's accessing has the code with side effects
}
</code>```

Note, this makes the top most layer (which should be the thinnest and most lacking in substance) the most highly dependent, however I think this makes sense, it's main purpose is to tie together whatever pieces of functionality it needs, while all the functionality really lies in the underlying libraries.

The interface pieces just exist for unit testing as much as anything, though modularity may always be needed later on. My preference is that IPC is used for access to both BL's at least, as well as DAL though that should be a more secured IPC interface. The form of IPC is irellevant, it could just be a memory mapped file or anything. I just think it's an important boundary to maintain independence for that time later when someone writes a better DAL than yours and all you have to do is run their DAL process instead of yours. Though maybe I'm just being a touch nutty for IPC, it's hardly necessary if you know you'll be able to maintain the boundaries between layers without needing any protections to safeguard against accidents/mistakes/other people.

Title: Approach on Software Development Architecture

Body:
I am planning to standardize our way of creating project for our new projects.

Currently we are using 3tier architecture where we have our ClassLibrary Project where it includes our Data Access Layer and Business Layer

Something like:

```<code>   Solution ClassLibrary
     >ClassLibrary Project :
          >DAL(folder)
               > DAL Classes
          >BAL(folder)
               > BAL Classes
</code>```

And this Class Library dll was reference on our presentation Layer Project which are the Application(web/desktop)

Something like:

```<code>     Solution WebUniversitySystem
     >Libraries(folder)
          > ClassLibrary.dll
     >WebUniversitySystem(Project):
          >Reference ClassLibrary.dll
          >Pages etc...
</code>```

Now i am planning to do is something like:

```<code> Solution WebUniversitySystem
     >DataAccess(Project)
     >BusinesLayer(Project)
          >Reference DAL
     >WebUniversitySystem(Project):
          >Reference BAL
          >Pages etc...
</code>```

Is this OK? Or there is a good approach that we can follow?

Body:
My main critique of your approach would be, don't make your BL directly depend on your DAL, put a layer of indirection in their where the BL receives the DAL via IOC or IPC (which is basically a form of IOC) Then the consumers of your BL get to choose what DAL it gets; If the consumer's a unit test it gives a mock DAL, if the consumer is that one annoying client for some reason they use a CSV DAL you hate maintaining, but for most consumers the BL is given a large DAL for enterprise use and about 20% of implemented consumers are the mobile versions presentation layer which gives the BL that in-memory DAL.

I'm a personal fan of having a shared block of data models, 2 BL's, one DAL, and a presentation layer in the MVC pattern.

Why 2 BL's? There is always a body of logic that lives at the DAL layer for actually translating the requested data into a data model, and even more complexity on the other way around, especially if you have any form of caching whatsoever. Usually people embed all of this into their DAL but end up paying a maintenance penalty they wouldn't have to if they made a separate layer above the DAL which receives DAL components in IOC and completes said logic.

The other BL then should in my opinion be idempotent in a functional paradigm with minimal if any side effects, side effects are what the dal is for.

So the dependency graph would be (layer: things it depends on):

DataModels: nothing
DAL: nothing
DALInterfaces: nothing
DALBL: DALInterfaces, DataModels
DALBLInterfaces: DALInterfaces, DataModels
BL: DataModels
BLInterfaces: DataModels
Presentation: DataModels, *Interfaces, some IOC framework or service client framework that turns the interfaces into concrete implementations.

Then the use is such that in your presentation you would do things like:

public MenuOption[] GetMenuOptions(string username, string password)
{
    DataModels.User currentUser = _securityBl.GetUserFromThread(Thread.CurrentThread);
    // remember no side effects in BL layer, just works from inputs, so needs be told the thread
    return _usersDalBl.GetMenuOptionsForUser(currentUser);
    // this dalBl was given a concrete Dal at construction, again
    // no *direct* side effects, only the dal it's accessing has the code with side effects
}

Note, this makes the top most layer (which should be the thinnest and most lacking in substance) the most highly dependent, however I think this makes sense, it's main purpose is to tie together whatever pieces of functionality it needs, while all the functionality really lies in the underlying libraries.

The interface pieces just exist for unit testing as much as anything, though modularity may always be needed later on. My preference is that IPC is used for access to both BL's at least, as well as DAL though that should be a more secured IPC interface. The form of IPC is irellevant, it could just be a memory mapped file or anything. I just think it's an important boundary to maintain independence for that time later when someone writes a better DAL than yours and all you have to do is run their DAL process instead of yours. Though maybe I'm just being a touch nutty for IPC, it's hardly necessary if you know you'll be able to maintain the boundaries between layers without needing any protections to safeguard against accidents/mistakes/other people.


问:
Software Management Tools for Agile Process Development
We would like to implement the Agile/ Scrum process in our daily software management, so as to provide better progress visibility and feature managements, here are some of the activities that we want to do:

Daily stand-up

Release cycles of 6 weeks with 3 2-week iterations.

Having a product back-log of tasks (integrate with bugzilla) and bugs estimated out.

Printing a daily burn down to make velocity visible. When used as motivator, it's great.

Easy feature development tracking and full blown visibility, especially for the sales and stake holders ( this means that it must be a web based tool).

My team is distributed, so physical whiteboards aren't feasible.

Is there such a web based tool that meets our needs? I heard icescrum may be one, but I've never used it so I don't know.

There are a few more suggestions as here, but I've never heard of them, anyone cares to elaborate or suggest new tools?

答:
Pivotal tracker does most what you asked for:
backlog, burn-down, velocity, etc.
See its Getting Started video and text guide on this page.</p>


答:
should a programmer take writing lessons to write better code?

No. A programmer should take writing lessons to learn to write better prose. A programmer should take programming lessons to learn to write better code. Despite some similarities, writing prose and writing code are quite different.

That's not to say that programmers shouldn't take writing classes. They should! Some reasons:

Writing is an essential skill for any educated person. You'll seem smarter if you can write well.

Despite their best efforts, programmers frequently need to communicate with other humans, often using the written word.

You learn skills beyond writing in writing classes, and those are often useful to programmers. For example, you'll learn to discuss other people's work without hurting their feelings, and you'll learn to accept criticism from others without taking it personally.

Title: Should a programmer take writing lessons to enhance code expressiveness?

Body:
Given that programmers are authors and write code to express abstract thoughts and concepts, and good code should be read by other programmers without difficulties and misunderstandings, should a programmer take writing lessons to write better code?

Abstracting concepts and real world problems/entities is an important part of writing good code, and a good mastery of the language used for coding should allow the programmer to express his thoughts more easily, or in a better way. Besides, when trying to write or rewrite some code to make it better, much time can be spent in deciding the names for functions, variables or data structures.

I think this could also help to avoid writing code with more than one meaning, often cause of misunderstanding between different programmers. Code should always express clearly its function unambiguously.


问:
What are some good examples of using pass by name?
When I write programs I using pass by value or pass by reference always seem to be logical methods. When learning about different programming languages I came across pass by name.

Pass by name is a parameter passing method that waits to evaluate the parameter value until it is used. See Stack Overflow pass by name question for more information on the method.

What I would like to know is: what are some good examples and/or reasons to use pass by name and should it be re-introduced into some more modern languages.

答:
Pass by name has some purpose.

Indeed we are saying that pass by name uses textual substitution or otherwise macro substitution.

If we are using pass by value or pass by reference we are merely passing values or addresses, but we can't pass an expression such as i*x[i]; (in pass by reference it evaluated into a temporary location whose address is passed ), but it is possible with pass by name.

For example if we want to perform the sum of the expression i*x[i] where i varies from 1 to 5 using a function, we can write a function that uses pass by reference as  written below (don't mind the syntax)

```<code>  *procedure sum (int low, int high, int i , real exp)
  {
       begin

         real S;
         S := 0;
         for i := low step 1 until high do
           {  S := S + Exp;
             Sum := S}
       end;*
 }
</code>```

then a call such as sum(1,5,i,x[i]) will find out the sum of series i*x[i], where Exp gets literally substituted for i*x[i].

Body:
Pass by name has some purpose.

Indeed we are saying that pass by name uses textual substitution or otherwise macro substitution.

If we are using pass by value or pass by reference we are merely passing values or addresses, but we can't pass an expression such as i*x[i]; (in pass by reference it evaluated into a temporary location whose address is passed ), but it is possible with pass by name.

For example if we want to perform the sum of the expression i*x[i] where i varies from 1 to 5 using a function, we can write a function that uses pass by reference as  written below (don't mind the syntax)

  *procedure sum (int low, int high, int i , real exp)
  {
       begin

         real S;
         S := 0;
         for i := low step 1 until high do
           {  S := S + Exp;
             Sum := S}
       end;*
 }

then a call such as sum(1,5,i,x[i]) will find out the sum of series i*x[i], where Exp gets literally substituted for i*x[i].


问:
Shared FIFO file descriptor
is ok to open fifo with one FD and share it with multiple threads?
or is it better to have multiple fds opened for the same fifo and share these fds with the threads?
BTW, I'll be doing write and read.

The environment is linux, C, pthreads

答:
Depends on what exactly you are going to do. Usually if you stick to the syscall-level interface (int-typed descriptors, methods read and write), one descriptor is ok, except if you want to have different settings (some blocking, some not and such).

Remember, that when there are multiple readers on fifo, random one of them will get the data and the switch from one reader to another may happen after any byte (because it depends on write granularity and internal implementation of the buffer in kernel), so you either need one fifo for each intended recipient or use single-byte messages.

Title: Shared FIFO file descriptor


问:
Get system info from C program?
I'm writing a little program in C that I want to use to output some system stats to my HD44780 16x2 character display. The system I'll be working with is a Debian ARM system and, although irrelevant, the display is on the GPIO header.(The system is a Raspberry Pi).

As an initial (somewhat unambitious) attempt, I'd like to start with something simple like RAM and CPU usage (I'm new to C).

I understand that if I make external command calls I need to fork() and execve() (or some equiv that will let me return the results), what I would like to know is how I go about getting the information I want in a nice clean format that I can use.

Surely I will not have to call (for e.g);

```<code>free -h
</code>```

And then use awk or similar to chop out the piece I want? There must be a cleaner way?

The question should be seen as more of a generic, what is best practice for getting info about the system in C (the RAM/CPU usage are just an initial example).

答: Give that you're on a modern Linux system, the information you're looking for is found in the pseudo-filesystem rooted at /proc/. Every process has a /proc/[pid] subdirectory, and other subdirectories provide a global status. E.g. /proc/meminfo is the source for free(1).

Title: Get system info from C program?


答:
If by "under" you mean a parent-child or composite-component relationship, this definitely makes no sense. Epics are big unrefined chunks of specification which you break down into user stories over time, not the other way around. Ditto for tasks and user stories.

Tools like TFS allow other types of relationships between work items (predecessor, related, concerned by, etc.) though.

So the answer to your question basically depends on whether your coworkers got the concept of epic completely wrong and want to reflect that in the tool, or just want some kind of weak link between epic and user story, which may be legitimate.

Title: Is it a good practice to have Epics under User Stories?

Body:
In my current team there is a practice of putting Epics under User Stories and sometimes even User Stories or Epics under Tasks! When questioned, the usual reply is: "if it is not a good practice then the project management tool would not have allowed doing so!" (IBM Rational Team Concert, for one does not prevent such practice.)

What do the experts here think about this?


问:
How to learn to make better estimates?
I suck at estimates. When someone asks me how long something will take, I don't even dare to make a guess since I will be completely off the mark. Usually I'm way too optimistic, and should probably multiply my guess with some large X factor...

How can I learn to make better estimates? It's not taught at my uni, and even though we have deadlines for all laborations I never think about how long something will actually take. Which I should. For everyone's sake (especially mine).

答:
I find it easiest to do the process of division to the minimal tasks as mentioned above work out each one and then double that estimate. Then I add them together and add fifty percent. That gives me an approximate project time in ideal conditions. If the work is practically going to be happening in parallel with others it's going to need longer. If you are going to have to wait for other people, expect them to take twice as long as you think it will. Waiting for content or feedback or other information often takes far longer than seems possible.

Where I work we work out a best case/expected case/worst case estimate for each step of the process, which is useful as a guide and also for evaluating how your estimates have worked out.

The technique is not ever so important except that you need to be able to combat the programmer's temptation to underestimate tasks, but what is important is being conservative about when you can deliver something. If it takes you seven weeks to build something and you promised eight weeks, you can come in a little early and look good for it or do some extra testing and be assured of reliability. If you promised six weeks you can look bad even if it's absolutely not your fault. If in doubt, guess conservatively.

Title: How to learn to make better estimates?


问:
How can we distribute a client app to other non-US businesses?
I'm working on an app which acts as a client for our web service.  We sell this service to businesses, and we want to distribute the app to their employees for free.  The app will be customised for each client.

If we were in the US, my understanding is that we'd ask them to enrol in the volume  purchasing program, and submit a version of our app for each business, for enterprise distribution at the free price point

However, the businesses aren't all in the US, so they can't enrol in the VPP.  They have thousands of employees, so promo codes won't be sufficient.  What are our alternatives?

答:
The iPad Volume Purchasing Program (VPP) is now available in Australia, Canada, France, Germany, Italy, Japan, New Zealand, Spain, UK along with the USA. See https://developer.apple.com/news/?id=09042012a and other news sites for more information.

If that is not available, you can use the iOS Enterprise Distribution mechanism. Basically, an organization enrols in the program, the developer supplies them the app then the organization can roll it out internally to all compatibly iOS devices that are enrolled with that organization.


问:
Scrum: How to work on one story at a time
I was nominated as scrum master in a new formed scrum team. We have already done some sprints. In the beginning I tried to make my team to work on one story at a time. But it didn't work.
My team had difficulties to distribute the tasks in a way that they can work simultaneously on one story. Maybe we are doing something wrong?

For example: we have a story to create a new dialog. We create the following tasks:

Create Model classes

Read model data from database

Connect model classes with view

Implement dialog handling

Save data on close

Test Documentation

Solution Description

Can theses tasks be done by more than one person at a time? The tasks - more or less - build upon each other.
Or do we design the tasks in a wrong way?

答:
What you want your team to do is called swarming, but not every backlog item can be swarmed around by the whole team. Common thought is that swarming requires some pre-conditions:

a cross functional, collocated team

a non trivial story

a definition of "done" that implies the involvement of the whole team

When breaking a story into tasks, the team should already be in swarming mode so that the generated tasks are compatible with swarming and can involve the whole team.

But be careful when using swarming too often or with too many people at once, as you might run into an overswarming problem, when some conflicts might appear between team members as they are too many working on the same item.

You might want to read Mike Cohn's Should a Team Swarm on to One Backlog Item at a Time? or this article I wrote (yesterday) which deals more specifically with bugs : To swarm or not to swarm


答: There are various library routines that provide system information, try taking a look at the sysinfo() call.

Title: Get system info from C program?

Body:
I'm writing a little program in C that I want to use to output some system stats to my HD44780 16x2 character display. The system I'll be working with is a Debian ARM system and, although irrelevant, the display is on the GPIO header.(The system is a Raspberry Pi).

As an initial (somewhat unambitious) attempt, I'd like to start with something simple like RAM and CPU usage (I'm new to C).

I understand that if I make external command calls I need to fork() and execve() (or some equiv that will let me return the results), what I would like to know is how I go about getting the information I want in a nice clean format that I can use.

Surely I will not have to call (for e.g);

```<code>free -h
</code>```

And then use awk or similar to chop out the piece I want? There must be a cleaner way?

The question should be seen as more of a generic, what is best practice for getting info about the system in C (the RAM/CPU usage are just an initial example).


问:
Is there a way to determine if a database has been altered, then to push new data to the Application
All our (my company) currently applications pull information from that database, is their a way to get the following types of databses to either push data or push an event to allow the application to pull data.

Access

SQL

Oracle

File systems (Files and folders)

The issue today is that most of our application spend a large amount of time constantly looking at databases and file system checking to see if data has changed . It would be better for the database to inform the application when data has changed. Are there tools within Visual studio to allow this or are there tools within the database / filesystem to do this?

All ready asked this on stack overflow but go no answer. I've been doing some more research but I cant seem to get any further. My manager has asked to investigate it as it would mean our applications are much quicker and efficient.

答:
The simple way to determine if the data has been altered is to put a timestamp column on each relevant table, and a trigger on insert and update that updates this row to Now.  If you want to make searching for new data fast, put an index on this column.  Then store in another table the last time you checked for updates.

When you check for updates, read the last update time, then run a query on each table for all rows where the timestamp > the last update time.  The tricky part here is when you reset the last update time. If you reset it immediately after you read it, you could get notified of some changes twice, whereas if you reset it after you're done processing updates, you could miss a few.  You'll have to decide which is more acceptable based on your business requirements.  (Or, if you want to make sure not to miss any, you'll need one row in the table that records the last update time for each table you're monitoring this way.)

This isn't exactly the database notifying you of what's changed, but it's getting the DB to do the bookkeeping for you, which greatly simplifies the work you have to do.

Doing it on a file system, follows the same basic principles, but it's a bit simpler because you have a timestamp built in to the file system.  You just need a recursive scan of the file system and filter out anything whose last update time is before the time you're looking for.


答:
You are not going to find anything Out of the box in any DB system that would do this for you.

I would recommend you Create a Stored procedure that checks for recently updated data a logs it to a Table. Have that SP run on a timer. Your APP would then only need to query   only one table and see all the changes across the system.

(That SP should also do some basic Clean up on the Table such as Deleting "Old rows)

If you need this to be more real-time, you would have to create a set of DB triggers that update this table.

This would move the code to back-end where it belongs (and where you want it).

Title: Is there a way to determine if a database has been altered, then to push new data to the Application

Body:
All our (my company) currently applications pull information from that database, is their a way to get the following types of databses to either push data or push an event to allow the application to pull data.

Access

SQL

Oracle

File systems (Files and folders)

The issue today is that most of our application spend a large amount of time constantly looking at databases and file system checking to see if data has changed . It would be better for the database to inform the application when data has changed. Are there tools within Visual studio to allow this or are there tools within the database / filesystem to do this?

All ready asked this on stack overflow but go no answer. I've been doing some more research but I cant seem to get any further. My manager has asked to investigate it as it would mean our applications are much quicker and efficient.


答:
Code by Charles Petzold is a very good introduction to the subject and describes the process of building a computer including how to construct adders, counters and RAM arrays and introduces machine code and assembly language and their relation to higher level languages. It's also a great read on the history of computing.

And I've just read this question on electronics.stackexchange which could be of use too

Title: Resources on learning to program in machine code?

Body:
I'm a student, fresh into programming and loving it, from Java to C++ and down to C. I moved backwards to the barebones and thought to go further down to Assembly.

But, to my surprise, a lot of people said it's not as fast as C and there is no use. They suggested learning either how to program a kernel or writing a C compiler. My dream is to learn to program in binary (machine code) or maybe program bare metal (program micro-controller physically) or write bios or boot loaders or something of that nature.

The only possible thing I heard after so much research is that a hex editor is the closest thing to machine language I could find in this age and era. Are there other things I'm unaware of? Are there any resources to learn to program in machine code? Preferably on a 8-bit micro-controller/microprocessor.

This question is similar to mine, but I'm interested in practical learning first and then understanding the theory.


问:
software architecture (OO design) refresher course
I am lead developer and team lead in a small RAD team. Deadlines are tight and we have to release often, which we do, and this is what keep the business happy.

While we (the development team) are trying to maintain the quality of the code (clean and short methods), I can't help but notice that the overall quality of the OO design&architecture is getting worse over the time - the library we are working on is gradually reducing itself to a "bag of functions". Well, we try to use the design patterns, but since we don't really have much time for a design as such we are mostly using the creational ones.

I have read Code Complete / Design Patterns (GOF & enterprise) / Progmatic Programmer / and many books from Effective XXX series. Should I re-read them again as I have read them a long time ago and forgotten quite a lot, or there are other / better OO design / software architeture books been published since then which I should definitely read?

Any ideas, recommendations on how can I get the situation under control and start improving the architecture. The way I see it - I will start improving the architectural / design quality of software components I am working on and then will start helping other team members once I find what is working for me.

答: Am I right in my assumption that you don't do any unit testing? Unit testing is a great way to show you where you design/architecture lacks... if you are not able to test classes in isolation, your design may be broken... if it is reeeaaally hard to write tests for your classes, this may also be a sign that the design could be improved. Unit testing taught me more about proper design than any book out there...</p>


问:
Best strategy for supporting multiple server communication from iPhone/android app?
I'm making an app that will be used in multiple hospitals in the US. As per HIPAA compliance requirement, every hospital will have its own server that complies with these requirements of ensuring patient data security, etc.

Now the task is that the app should communicate with a particular server based on the login info. An additional requirement is that new hospitals(servers) are likely to be added along the way, even after the app is available on the market.

So basically, according to some login credentials, the app should communicate with the server of the hospital assigned to that person. One pretty crude way is to set up our own server which links the hospitals with the login info and accordingly, provides a base-url for data exchange. Is there a more efficient way to handle this?

答:
If users have to log in, you have a DB to keep the information about users, I suppose. And if there is a security issue (I suppose there is), you have two options:

keep the DB in the device. Information should be securely encrypted in this case. But still I wouldn't recommend you do this: Android applications are easy to crack, so anyone could get the original source-code and decrypt info in the DB. Some applications don't even have registration on their mobile version for security reasons.

have the DB on a server. This is much more secure, because the information is kept only in one place. In this case logging in could be done via the server, which would determine the IP address of the hospitals' servers and send that data to the devices.


答:
Giving releases often means that the code is changing all the time: small improvements, new features, additional functionality, etc. So the main rule (as my college says) is to keep in mind that whatever you write today will be changed tomorrow. The whole system should be extremely flexible and simple, so that changes will not break it's architecture or cause any other problems.

If you don't have enough time to design everything well, I'm pretty sure it's your management's fault. They keep pushing you, so you have to produce working code all the time. Try to convince them that creating good design from the beginning is essential: it will save time in future. Otherwise you risk to have a pile of working but unmanageable code. Besides, the better the design is, the less time coding requires. When everything is thought out thoroughly, there's very little left to do.

You could also consider code reviewing. Development will take longer, but a lot more time will be saved on fixing bugs.

In the company I work, every piece of somewhat big design is discussed with our team-leader. Nothing is coded without his OK. I assume, you should be the very person in your team who would approve design. If you think you don't have enough skills, you could do this together with other members of your team, who are most skillful. During code reviews you could gather the whole team and tell them about those improvements: how and why they were made. This is important, because (a) everyone will learn and (b) there is a big chance you'll get some good ideas from you less experienced colleges.

Title: software architecture (OO design) refresher course

Body:
I am lead developer and team lead in a small RAD team. Deadlines are tight and we have to release often, which we do, and this is what keep the business happy.

While we (the development team) are trying to maintain the quality of the code (clean and short methods), I can't help but notice that the overall quality of the OO design&architecture is getting worse over the time - the library we are working on is gradually reducing itself to a "bag of functions". Well, we try to use the design patterns, but since we don't really have much time for a design as such we are mostly using the creational ones.

I have read Code Complete / Design Patterns (GOF & enterprise) / Progmatic Programmer / and many books from Effective XXX series. Should I re-read them again as I have read them a long time ago and forgotten quite a lot, or there are other / better OO design / software architeture books been published since then which I should definitely read?

Any ideas, recommendations on how can I get the situation under control and start improving the architecture. The way I see it - I will start improving the architectural / design quality of software components I am working on and then will start helping other team members once I find what is working for me.


问:
Checking timeouts made more readable
I have several situations where I need to control timeouts in a technical application. Either in a loop or as a simple check. Of course – handling this is really easy, but none of these is looking cute.

To clarify, here is some C# (Pseudo) code:

```<code>private DateTime girlWentIntoBathroom;
girlWentIntoBathroom = DateTime.Now;

do
{
  // do something
} while (girlWentIntoBathroom.AddSeconds(10) > DateTime.Now);
</code>```

or

```<code>if (girlWentIntoBathroom.AddSeconds(10) > DateTime.Now)
  MessageBox.Show("Wait a little longer");
else
  MessageBox.Show("Knock louder");
</code>```

Now I was inspired by something a saw in Ruby on StackOverflow:

Now I’m wondering if this construct can be made more readable using extension methods. My goal is something that can be read like

“If girlWentIntoBathroom is more than 10 seconds ago”

1st attempt

```<code>if (girlWentIntoBathroom > (10).Seconds().Ago())
  MessageBox.Show("Wait a little longer");
else
  MessageBox.Show("Knock louder");
</code>```

So I wrote an extension for integer that converts the integer into a TimeSpan

```<code>public static TimeSpan Seconds(this int amount)
{
  return new TimeSpan(0, 0, amount);
}
</code>```

After that, I wrote an extension for TimeSpan like this:

```<code>public static DateTime Ago(this TimeSpan diff)
{
  return DateTime.Now.Add(-diff);
}
</code>```

This works fine so far, but has a great disadvantage. The logic is inverted! Since girlWentIntoBathroom is a timestamp in the past, the right side of the equation needs to count backwards: impossible.
Just inverting the equation is no solution, because it will invert the read sentence as well.

2nd attempt

So I tried something new:

```<code>if (girlWentIntoBathroom.IsMoreThan(10).SecondsAgo())
  MessageBox.Show("Knock louder");
else
  MessageBox.Show("Wait a little longer");
</code>```

IsMoreThan() needs to transport the past timestamp as well as the span for the extension SecondsAgo(). It could be:

```<code>public static DateWithIntegerSpan IsMoreThan(this DateTime baseTime, int span)
{
  return new DateWithIntegerSpan() { Date = baseTime, Span = span };
}
</code>```

Where DateWithIntegerSpan is simply:

```<code>public class DateWithIntegerSpan
{
  public DateTime Date {get; set;}
  public int Span { get; set; }
}
</code>```

And SecondsAgo() is

```<code>public static bool SecondsAgo(this DateWithIntegerSpan dateAndSpan)
{
  return dateAndSpan.Date.Add(new TimeSpan(0, 0, dateAndSpan.Span)) < DateTime.Now;
}
</code>```

Using this approach, the English sentence matches the expected behavior. But the disadvantage is, that I need a helping class (DateWithIntegerSpan).

Has anyone an idea to make checking timeouts look more cute and closer to a readable sentence? Am I a little too insane thinking about something minor like this?

答:
You are trying to solve a none existent problem. Programming is not about writing proper english sentences (and I'm not a native english speaker, so pardon the english).

I find this code hard to read:

```<code>if (girlWentIntoBathroom.IsMoreThan(10).SecondsAgo())
</code>```

I have no idea that girlWentIntoBathroom contains a date/time. I have to read the method SecondsAgo to udnerstand that, and then go back to the beginning of the line and re-read everything to understand what it does.

```<code>if (girlWentIntoBathroom > 10.Seconds().Ago())
</code>```

Is more readable, I can by looking at 10.Seconds() tell that girlWentIntoBathroom is some kind of date/time unit.

While this is enough for me:

```<code>if (girlWentIntoBathroom > TimeSpan.FromSeconds(10).Ago())
</code>```

Since I'm used to the TimeSpan structure.

This is just fine too:

```<code>if (girlWentIntoBathroom > DateTime.Now.AddSeconds(-10))
</code>```

Since we are after all programmers and AddSeconds(-10) will therefore make sense.

Title: Checking timeouts made more readable

Body:
You are trying to solve a none existent problem. Programming is not about writing proper english sentences (and I'm not a native english speaker, so pardon the english).

I find this code hard to read:

if (girlWentIntoBathroom.IsMoreThan(10).SecondsAgo())

I have no idea that girlWentIntoBathroom contains a date/time. I have to read the method SecondsAgo to udnerstand that, and then go back to the beginning of the line and re-read everything to understand what it does.

if (girlWentIntoBathroom > 10.Seconds().Ago())

Is more readable, I can by looking at 10.Seconds() tell that girlWentIntoBathroom is some kind of date/time unit.

While this is enough for me:

if (girlWentIntoBathroom > TimeSpan.FromSeconds(10).Ago())

Since I'm used to the TimeSpan structure.

This is just fine too:

if (girlWentIntoBathroom > DateTime.Now.AddSeconds(-10))

Since we are after all programmers and AddSeconds(-10) will therefore make sense.


问:
How to take a step back and look at code with fresh eyes?
I've spent the last year as a one-man team developing a rich-client application (35,000+ LoC, for what it's worth). It's currently stable and in production. However, I know that my skills were rusty at the beginning of the project, so without a doubt there are major issues in the code. At this point, most of the issues are in architecture, structure, and interactions -- the easy problems, even architecture/design problems, have already been weeded out.

Unfortunately, I've spent so much time with this project that I'm having a hard time thinking outside of it -- approaching it from a new perspective to see the flaws deeply buried or inherent in the design.

How do I step outside my head and outside my code so I can get a fresh look and make it better?

答:
Ways to approach this:

Find someone familiar with the technology and business problem and talk it through. This may be hard in a single-person team but is generally the best option.

Work on a different project for a while. This also may be difficult but even taking a week's break can give you a fresh perspective.

Look at similar projects or products, such as open source products if any exist. Be careful not to copy code but they may have approached the idea completely differently.

Learn a new language, library or framework. The techniques involved may give you insight how to approach the same problems you have differently.

Read a good book/blog/magazine on design or the language/framework. I am not sure what level of skill you are at, but there are lots of alternatives in other answers on this site.

If you have specific examples you want addressed, perhaps post them here.


答: Have another person look at your code.  If you can't find another person to look at it, write up a complete description of the interaction like you're going to show it to another person.  The process of trying to explain your decisions to another person (even if its just for practice) can help you really think out WHY you're doing things a certain way and help you see any holes in your logic.</p>

Title: How to take a step back and look at code with fresh eyes?

Body:
I've spent the last year as a one-man team developing a rich-client application (35,000+ LoC, for what it's worth). It's currently stable and in production. However, I know that my skills were rusty at the beginning of the project, so without a doubt there are major issues in the code. At this point, most of the issues are in architecture, structure, and interactions -- the easy problems, even architecture/design problems, have already been weeded out.

Unfortunately, I've spent so much time with this project that I'm having a hard time thinking outside of it -- approaching it from a new perspective to see the flaws deeply buried or inherent in the design.

How do I step outside my head and outside my code so I can get a fresh look and make it better?


答:
Keep learning and expanding your skills. It's tough to know what you don't know, but when you see it, that "aha" moment will hit you. It could come from learning another language or design pattern.

You're going to be asked to make a change. You may find parts of your code that aren't so flexible and will require a lot of rework. This isn't necessarily a failure because you can't think of everything at first.

Users will start to complain. Just when you think everything is great...


问:
What are the fundamental differences between C and C++?
Many tend to write "C/C++", as if they were the same thing. Although they share many similarities, they are clearly not the same.

But what are really the fundamental differences between C and C++? Is C++ an enhanced version of C, or are there features in C which do not exist in C++?

答:
In general, everything that exists in C is supported in C++. Obviously the opposite is absolutely false.

Simply speaking, C++ is object oriented (so, for examples, you have classes), C is not.

C++ has a boolean type C89 doesn't.

They are different languages. They just share most of the syntax.


问:
Generating CMakeLists.txt
I got a bunch of C++ sources files and headers. They may use external libraries such as Boost e.g. I am interested in the process of building binaries for Windows and *nix.

Makefiles (*nix) and .vcproj (Windows) call compilers with some specifications such as the order of compilation, compilation options and stuff.

CMakeLists.txt can be used by CMake to build either makefiles or .vcproj and use very helpful commands such as recursive search of files, automatic linkage with known libraries, installers, variables that can be used in source files...

Is there any existing tool that would generate a CMakeLists.txt from specified options ? Options could be like : scan this folder and make a library out of it, then scan this other folder and make an executable and automatically link both with Boost as well along with a user friendly installer with generated INSTALL.txt and README.txt. Something very powerful like that.

答:
I recently started learning CMake myself, and like Delnan mentions in his comment there is really no point in wrapping the creation of those scripts further in some kind of tool.  The problems that you are trying to solve are pretty much the purpose of CMake and its reason for existence.

In fact, what you say you want to do sounds a lot like what the CMakeLists.txt for a project actually would do (without the installation part, which is slightly more involved depending on your needs).

e.g. scanning a folder for source and turning it into a lib is at its heart just a few commands:

```<code>cmake_minimum_required(VERSION 2.8)
project(YourProject)

# This is a built-in utility to grab all the source files from a specific
# location into a list
AUX_SOURCE_DIRECTORY(. LOG_SOURCES)

# This is all you need to do to tell CMake that a specific list of files
# should be built as a library (shared in this case)
add_library(Logging SHARED ${LOG_SOURCES})
</code>```

The above doesn't yet link any other libraries automatically, or deal with compiler settings, but all of that stuff is possible and relatively straightforward once you start wrapping your head around the CMake-way.

Title: Generating CMakeLists.txt

Body:
I recently started learning CMake myself, and like Delnan mentions in his comment there is really no point in wrapping the creation of those scripts further in some kind of tool.  The problems that you are trying to solve are pretty much the purpose of CMake and its reason for existence.

In fact, what you say you want to do sounds a lot like what the CMakeLists.txt for a project actually would do (without the installation part, which is slightly more involved depending on your needs).

e.g. scanning a folder for source and turning it into a lib is at its heart just a few commands:

cmake_minimum_required(VERSION 2.8)
project(YourProject)

# This is a built-in utility to grab all the source files from a specific
# location into a list
AUX_SOURCE_DIRECTORY(. LOG_SOURCES)

# This is all you need to do to tell CMake that a specific list of files
# should be built as a library (shared in this case)
add_library(Logging SHARED ${LOG_SOURCES})

The above doesn't yet link any other libraries automatically, or deal with compiler settings, but all of that stuff is possible and relatively straightforward once you start wrapping your head around the CMake-way.


答:
A short memory helps.  I've been known to complain about the "idiot" that changed something a week ago, only to find from source control it was me.

A good first step is to identify code that could be improved.  Look in your source control for the files that change most often.  Which code is the hardest to work with?  Which code produces the most bugs?  What kinds of changes cause a ripple effect throughout the code?  At this stage, you don't have to know why the code is troublesome, just that it's troublesome.

Once you've identified areas to work on, then try to figure out what the problem actually is.  There are books that take a systematic approach to categorizing design problems.  Look at Martin Fowler's Refactoring, Herb Sutter's C++ Coding Standards, Robert Martin's Clean Code, etc.  They have a bunch of "rules" that let you look at your code in an objective way.

Once you've identified what the problem likely is, then try out different ways to fix it.  For example, if the rule you broke is "prefer composition over inheritance," then change it to composition and see how it feels.

Obviously, it can be helpful to have someone else look at the code, but it's not always as helpful as you might think, because you are much more familiar with the kinds of problems the code causes than anyone else, and the reasons behind the design.  Learning some ways to objectively evaluate your own design will pay big dividends.


答:
Don't sweat the small stuff.

Everyone could code better. We do things fast and then realize a couple of weeks after that it could have been done more efficiently.  The point is that 90% of your code is probably good enough.

Look over your bug logs and find the routines that might be causing issues.  As you find the bugs, you can also review the code and think about what might make the code more efficient.  Most of the time, you'll realize that beyond fixing the bug itself, you won't be able to make a noticeable improvement, but sometimes, you'll realize that there's a better way to do something.

Talk to users and see where they are noticing issues, either UX or speed issues.  Fix these issues, with an eye for trying to improve your code.

At some point, you will discover that your code has become too brittle and that there is simply no way to make the changes that you need to do.  Then think about how you could have made the system more flexible, either via APIs or test driven development.  In many cases, you'll discover that you can just start putting these APIs into the code, with not a huge amount of changes.  In other cases, you'll realize that the effort of improving the code isn't worth it.

Incremental changes can be hard.  The goal is to not entirely re-write the code base if you don't have to.  Sure, you're a better programmer now than you were a year ago, but what you have must be working right now.  5 years from now, when a junior programmer complains to you about the legacy code they have to try to fix, just smile and nod, and don't admit that you wrote it.


答:
My two suggestions would be on the one hand, go back to the fundamentals, and on the other hand add to those fundamentals in your tool box:

Back to the fundamentals:
Design principles are the fundamental elements that drive design patterns, without principles to strive for all those formal patterns wouldn't exist. Start with SOLID http://en.wikipedia.org/wiki/SOLID_(object-oriented_design) and go into pieces of the code you feel have become bumpy and start assessing which principles are being broken and why. For future code you write, with each class or method or design you begin to implement, ask yourself if it's obeying the principles or breaking any of them.

Adding fundamentals:
You mention OO and clearly have a strong drive towards this direction, but OO designs can often be improved through understanding of the functional paradigm and how it achieves compliance with design principles. If you haven't learned any functional languages, go learn Haskell or f# or Clojure or any of them really (Haskell will literally give you a headache, and simultaneously change your mind for you). Just learning and practicing one of these for a month in your spare time will give you new tools which will allow you to more easily and comprehensively obey good design principles in scenarios where maybe the OO approaches just didn't quite meet good design.


问:
Which language came first with parallel assignment?
When I discovered  that python has parallel assignment I thought is pretty cool.

Recently I discovered parallel assignment works also in ruby.

For people that don't know it: x,y = y,x in ruby, python this swaps x and y values .

Which language came first with parallel assignment, python? or was it other language?

答:
CPL introduced the feature in 1963, calling it simultaneous assignment. From D.W. Barron et al., "The main features of CPL" (page 140):

24. Simultaneous assignment commands

The general form of an assignment command can now be given. Normally this is an expression yielding an LH value, followed by :=, followed by an expression yielding an RH value. However, if an explicit list is written on the left-hand side then the right-hand side is either an explicit list, or a list expression; in the latter case the transfer function Members is automatically invoked. In this form the two explicit lists must contain the same number of members, and the command denotes a simultaneous assignment of each right-hand member to the corresponding left-hand member. Thus, if L is a list variable and a, b, c are real variables,

L := a, b, c

is an assignment to the list variable, while

a, b, c := L

a, b := b,a

are simultaneous assignments.