问:
Web application structure review
I'd like to have suggestions about the structure of my web application.

What the app does:

My app receives files from about 800 scanners around my country and the users see the scanned pages into this web application, then they can organize the pages in groups, choose which one keep and which one discard, and insert some additional information to each group.

After this, another kind of user check what the first type of user has did and approve or discard each group of pages.

After that, a procedure on another server transforms each group in PDF and TIFF multi page.

After this little background to have an idea of what my web app does, this is how the files tree looks:

```<code>ajax
|- ajaxaction1.php
|- ajaxactionx.php

cache
|- xxx_xxxxxxxxxxxx.gif

css
|- style.min.css
|- font-awesome.min.css

fonts
| here there are the fonts needed by font-awesome.min.css

js
|-functions.min.js
|-main.min.js
|-jquery.x.x.x.min.js
|-jquery.x.x.x.min.map
|-jquery.lib1.min.js
|-jquery.libx.min.js

views
|-features.php
|-features.tpl

config.ini // DB configuration file
index.php // the page that is used by the application
init.php // read description below
web.config // used to restrict access to only the right files
</code>```

ajax:

Folder where there are PHP scripts that are called by Ajax to perform INSERT and UPDATE queries to database.

cache:

Folder where there are temporary .gif files extracted from the scanned pages sent from the scanners to my server.

These images stay here just the time needed to process them, then them are deleted.

css:

Here are stored the only two css files needed by my web app.

js:

in this folder are stored all the JS files.

functions.min.js is a file where I declare all the javascript functions

main.min.js is where the functions are called

views:

Here I store the PHP and TPL files that are loaded by AJAX to show the requested pages.

The PHP files perform queries to DB and prepare a matrix, then the TPL files get the matrix and print the markup.

init.php:
In this file I perform the connection to the database and initialize the $pdo session.

I also check that the user is correctly logged in (I use a single sign on provided by an external software to login users).

Here I also set some common PHP function used in the other PHP scripts.

This script is included in each PHP page.

I'd like to have reviews about how I've organized the files and folders of my application.

答:
Your directory structure is clear and organized in a good way. It is a very good idea to organize in the way you have done.

What you could possibly do later, if needed (mostly depending on the current filesize), is to split your init.php into separate parts such as:

functions-database.php

functions-login.php

functions-common.php

I have to say that I especially like the filename 'font-awesome.min.css'

OwnerDisplayName: Fez Vrasta

Title: Web application structure review

OwnerDisplayName: Simon André Forsberg


答:
Separation

For external dependencies (third-parties libraries), I would suggest separating them from your custom one.

Create a lib folder under css and js.

Make sure the relative image path is amended in css files if any.

```<code>css
|- style.min.css
   lib
   |- font-awesome.min.css

js
|- functions.min.js
|- main.min.js
   lib
   |-jquery.x.x.x.min.js
   |-jquery.x.x.x.min.map
   |-jquery.lib1.min.js
   |-jquery.libx.min.js
</code>```

OR

```<code>js
|- functions.min.js
|- main.min.js
   lib
       |-jquery
           |-jquery.x.x.x.min.js
           |-jquery.x.x.x.min.map
           |-jquery.lib1.min.js
           |-jquery.libx.min.js
</code>```

So you are less likely to edit those frameworks and libraries accidentally.

Consistency

Use either singular or plural form of noun appropriately.

Change folder cache to caches for matching the views.

Includes

As being said in another answer, in your case, modules should be separated into several files. Not only for the purpose of a clear directory hierarchy, but also for the performance and security issue.

Extra

Use images folder for storing images.

Use specific folder (e.g. data) for saving the data.

For more examples and practices, you can refer to SO: Directory Structure for MVC

ContentLicense: CC BY-SA 3.0

Title: Web application structure review

Body:
I'd like to have suggestions about the structure of my web application.

What the app does:

My app receives files from about 800 scanners around my country and the users see the scanned pages into this web application, then they can organize the pages in groups, choose which one keep and which one discard, and insert some additional information to each group.

After this, another kind of user check what the first type of user has did and approve or discard each group of pages.

After that, a procedure on another server transforms each group in PDF and TIFF multi page.

After this little background to have an idea of what my web app does, this is how the files tree looks:

```<code>ajax
|- ajaxaction1.php
|- ajaxactionx.php

cache
|- xxx_xxxxxxxxxxxx.gif

css
|- style.min.css
|- font-awesome.min.css

fonts
| here there are the fonts needed by font-awesome.min.css

js
|-functions.min.js
|-main.min.js
|-jquery.x.x.x.min.js
|-jquery.x.x.x.min.map
|-jquery.lib1.min.js
|-jquery.libx.min.js

views
|-features.php
|-features.tpl

config.ini // DB configuration file
index.php // the page that is used by the application
init.php // read description below
web.config // used to restrict access to only the right files
</code>```

ajax:

Folder where there are PHP scripts that are called by Ajax to perform INSERT and UPDATE queries to database.

cache:

Folder where there are temporary .gif files extracted from the scanned pages sent from the scanners to my server.

These images stay here just the time needed to process them, then them are deleted.

css:

Here are stored the only two css files needed by my web app.

js:

in this folder are stored all the JS files.

functions.min.js is a file where I declare all the javascript functions

main.min.js is where the functions are called

views:

Here I store the PHP and TPL files that are loaded by AJAX to show the requested pages.

The PHP files perform queries to DB and prepare a matrix, then the TPL files get the matrix and print the markup.

init.php:
In this file I perform the connection to the database and initialize the $pdo session.

I also check that the user is correctly logged in (I use a single sign on provided by an external software to login users).

Here I also set some common PHP function used in the other PHP scripts.

This script is included in each PHP page.

I'd like to have reviews about how I've organized the files and folders of my application.

Body:
Separation

For external dependencies (third-parties libraries), I would suggest separating them from your custom one.

Create a lib folder under css and js.

Make sure the relative image path is amended in css files if any.

css
|- style.min.css
   lib
   |- font-awesome.min.css

js
|- functions.min.js
|- main.min.js
   lib
   |-jquery.x.x.x.min.js
   |-jquery.x.x.x.min.map
   |-jquery.lib1.min.js
   |-jquery.libx.min.js

OR

js
|- functions.min.js
|- main.min.js
   lib
       |-jquery
           |-jquery.x.x.x.min.js
           |-jquery.x.x.x.min.map
           |-jquery.lib1.min.js
           |-jquery.libx.min.js

So you are less likely to edit those frameworks and libraries accidentally.

Consistency

Use either singular or plural form of noun appropriately.

Change folder cache to caches for matching the views.

Includes

As being said in another answer, in your case, modules should be separated into several files. Not only for the purpose of a clear directory hierarchy, but also for the performance and security issue.

Extra

Use images folder for storing images.

Use specific folder (e.g. data) for saving the data.

For more examples and practices, you can refer to SO: Directory Structure for MVC

OwnerDisplayName: Ivan Chau


问:
Data Transfer Best Practices
At my company we have some vendors that we transfer data to and from. Sometimes the data is pulled into our local SQL database for business reporting. Other times we pull data from one vendor, transform it, and then transfer it to another vendor's FTP server.

The guy I replaced has a couple of generic SFTP Push/Pull console applications that transfer data to/from these vendors. Then he has other applications that do the data imports to the SQL database or transforms the data and leaves it out in a directory to be pushed to the vendor.

Every once in a while we will have problems with these processes not finding the file needed and I have to go back and run these manually to load the data. It seems to me that it would be more reliable if these processes just did their own FTP push/pull functions so we don't run into scheduling problems. Are there any standard practices that I can implement that would be more reliable or do I need to just tweak what I have now? I'm in a Windows/.NET environment by the way.

答:
First of all, having the ftp push/pull mechanism separated from the core processing sounds to me a good design, since it will allow to test the core processing separately and plug the parts easily together in a different way if needed. This is a good example of separation of concerns.

Every once in a while we will have problems with these processes not finding the file needed

Before thinking about any solution with the chance of causing probably more problems than it will solve, make sure you know what the root cause of the problem is. Is it because job A (pulling the data) puts the file in a wrong folder where job B (pushing the file data) does not expect it? Then you need a better way to pass the file path from job A to job B in a reliable way.

Or is it because sometimes job B starts too early, before the output of job A has arrived completely? Well, then you need a better mechanism to trigger the start of job B. Is it not possible to put A and B in a command script which makes sure B does only start when A is complete? Maybe you have to implement a polling mechanism in job B which makes sure it does not start its processing until the output of job A is available. Maybe you have to implement a loop around job A to make sure it will try to download a file again when the first attempt has failed. It may be a good idea to let the ftp process download all data into a temporary file first, and rename that file as a final step when it is complete. Renaming is an atomic operation on most file systems, so this makes the file only visible to the following processes when it is ready for further processing. Another possible technique is to work with some "lock files", prohibiting shared access to a file "X" as long as "X.lock" exists.

So, IMHO the architecture you described is not brittle per se, but you have to provide a reasonable amount of synchronization and failure tolerance around your processes.

Title: Data Transfer Best Practices


问:
Ensuring transactional consistency with DDD
I am starting out with DDD and understand that aggregate roots are used to ensure transnational consistency. We should not modify multiple aggregates in one application service.

I would like to know however how to deal with the following situation.

I have an aggregate root called Products.

There is also an aggregate root called Group.

Both have Id's, and can be edited independently.

Multiple Products can point to the same Group.

I have an application service that can change a product's group:

ProductService.ChangeProductGroup(string productId, string groupId)

Check group exists

Get product from repository

Set its group

Write the product back to repository

I also have an application service where the group can be deleted:

GroupService.DeleteGroup(string groupId)
 1. Get products from repository whose groupId is set to provided groupId, ensure count is 0 or abort
 2. Delete group from groups repository
 3. Save changes

My question is the following scenario, what would happen if:

In the ProductService.ChangeProductGroup, we check the group exists (it does), then just after this check a separate user deletes the productGroup (via the other GroupService.DeleteGroup). In this case we set a reference to a product which has just been deleted?

Is this a flaw in my design in that i should use a different domain design (adding additional elements if necessary), or would i have to use transactions?

答:
We have the same issue.

And I se no way to solve this problem but with transactions or with consistency check at the DB to get an exception in the worst case.

You can also use pessimistic lock, blocking aggregate root or only its parts for other clients until business transaction is completed what is to some extent equivalent to serializable transaction.

The way you go heavily depends on your system and business logic.

Concurrency is not an easy task at all.
 Even if you can detect a problem how will you resolve it? Just cancel the operation or allow user to 'merge' changes?

We use Entity Framework and EF6 uses read_commited_snapshot by default, so two consecutive reads from repository can give us inconsistent data. We just keep that in mind for the future when business processes will be more clearly outlined and we can make infromed decision. And yes we still check consistency at model level as you do. This at least allows to test BL separately from DB.

I also suggest you to think over repository consistency in case you have 'long' business transactions. It is quite tricky as it turned out.


答:
Are there any standard practices that I can implement that would be more reliable or do I need to just tweak what I have now?

Tweak what you have now. For this kind of thing you probably have quite a few custom requirements - retries, availability windows, notifications, backing up, zipping. If it's working 90% of the time see if you can get it up to 99% of the time. Add a whole bunch of logging and exception handling and take it from there. Maybe run it manually yourself every day for 2 weeks to see if you can get it to fail.

I have yet to find a great application that takes care of SFTP'ing stuff to and from other servers with the option of setting availability windows, retries, notifications, etc. I believe SQL Server can do it. AFAIK, there's no "standard". Hmm maybe I should code something up and sell it :)

Title: Data Transfer Best Practices

Body:
At my company we have some vendors that we transfer data to and from. Sometimes the data is pulled into our local SQL database for business reporting. Other times we pull data from one vendor, transform it, and then transfer it to another vendor's FTP server.

The guy I replaced has a couple of generic SFTP Push/Pull console applications that transfer data to/from these vendors. Then he has other applications that do the data imports to the SQL database or transforms the data and leaves it out in a directory to be pushed to the vendor.

Every once in a while we will have problems with these processes not finding the file needed and I have to go back and run these manually to load the data. It seems to me that it would be more reliable if these processes just did their own FTP push/pull functions so we don't run into scheduling problems. Are there any standard practices that I can implement that would be more reliable or do I need to just tweak what I have now? I'm in a Windows/.NET environment by the way.


问:
Does a Mixin By Definition Allow Storing Data in Mixin-Level Instance Variables?
Several implementations of mixins (e.g. Ruby mixin, Scala trait) include support for storing data (e.g. variables, properties) between method calls in instance variables. There was a bit of debate in this question about whether or not a Java virtual extension method qualified as a mixin because they cannot store data in this way; all variables are inputted and outputted within the scope of the method call and cannot be stored in an instance variable. Essentially, there was debate about what a "mixin" by definition is and whether or not implementations in Ruby and whatnot go beyond the commonly recognized definition of the programming concept.

Unfortunately, the definition of a mixin seem rather vague in this regard. For instance, Wikipedia says the following:

With mixins the class definition defines only the attributes and parameters associated with that class; methods are left to be defined elsewhere, as in Flavors and CLOS, and are organized in "generic functions". These generic functions are functions that are defined in multiple cases (methods) by type dispatch and method combinations.

The above says that a mixin defines attributes, but doesn't cite sources that might clarify this. However, every other definition simply fails to mention whether or not mixins allow storing data or if they are limited to methods. To further add confusion, Wikipedia earlier describes mixins as an interface with implemented methods, but interfaces can't store instance variables. I tried to find out how it was defined in Flavors, which was the first programming language to use something called "mixins", but I couldn't find enough information online about it.

So can a mixin by definition allow storing data? Or is this something that is ambiguous and is left up to the programming language to decide?

答:
The paper Mixin-based Inheritance by Bracha and Cook [PDF] shows that inheritance as found in the languages Smalltalk, Beta and CLOS can be reinterpreted as specializations of mixin inheritance.

The main point here is that inheritance can be viewed as a linear application of abstract deltas to a base class, e.g.

```<code>class Foo {
  int num = 42;
  int doStuff() { return num; }
}

class Bar extends Foo {
  void otherStuff() { return; }
}
</code>```

– here we could interpret both classes as deltas: The Foo mixin adds a doStuff method and a num member, while Bar adds otherStuff. However, mixins can't be instantiated on their own (are abstract). Expressed this way, with mixin composition via the ⊕ operator:

```<code>mixin MFoo {
  int num = 42;
  int doStuff() { return num; }
}

class Foo = MFoo ⊕ Object;

mixin MBar {
  void otherStuff() { return; }
}

class Bar = MBar ⊕ Foo
          = MBar ⊕ (MFoo ⊕ Object)
</code>```

Classical single inheritance is a specialization of mixins where each delta can only be applied to a single superclass (MBar can only be applied to Foo, but not also to Baz).

If single class inheritance can be viewed as a specialization of mixins, then mixins allow the inheritance of data! However, a specific specialization of mixins need not require this. Both class inheritance and interfaces are specializations of mixins.

Java's extension methods do not allow storage of state, thus Java 8 interfaces are not able to model class inheritance. Therefore, these interfaces are not mixins in the sense of Bracha and Cook. They do however offer mixin-like functionality in that they allow to inherit functionality from multiple types, thus providing a weak kind of multiple inheritance.

Two points remain worth mentioning, although they are tangential to my argument:

First, nowadays traits are all the rage. This is an extension of mixins that doesn't require linear composition. All newer mixin-like systems actually implement traits or at least call them such.

Second, the design rationale for extension methods in Java 8 is not primarily to add mixins, traits, or multiple inheritance but rather to add the ability to retroactively extend existing interfaces to use new methods. It is intended that these extension methods are overridden by implementing classes. Importantly, this allows to update the Collection interface to include methods like the higher-order function map without breaking code that implemented Collection during Java 7 times and thus has no implementation for map.

Body:
The paper Mixin-based Inheritance by Bracha and Cook [PDF] shows that inheritance as found in the languages Smalltalk, Beta and CLOS can be reinterpreted as specializations of mixin inheritance.

The main point here is that inheritance can be viewed as a linear application of abstract deltas to a base class, e.g.

class Foo {
  int num = 42;
  int doStuff() { return num; }
}

class Bar extends Foo {
  void otherStuff() { return; }
}

– here we could interpret both classes as deltas: The Foo mixin adds a doStuff method and a num member, while Bar adds otherStuff. However, mixins can't be instantiated on their own (are abstract). Expressed this way, with mixin composition via the ⊕ operator:

mixin MFoo {
  int num = 42;
  int doStuff() { return num; }
}

class Foo = MFoo ⊕ Object;

mixin MBar {
  void otherStuff() { return; }
}

class Bar = MBar ⊕ Foo
          = MBar ⊕ (MFoo ⊕ Object)

Classical single inheritance is a specialization of mixins where each delta can only be applied to a single superclass (MBar can only be applied to Foo, but not also to Baz).

If single class inheritance can be viewed as a specialization of mixins, then mixins allow the inheritance of data! However, a specific specialization of mixins need not require this. Both class inheritance and interfaces are specializations of mixins.

Java's extension methods do not allow storage of state, thus Java 8 interfaces are not able to model class inheritance. Therefore, these interfaces are not mixins in the sense of Bracha and Cook. They do however offer mixin-like functionality in that they allow to inherit functionality from multiple types, thus providing a weak kind of multiple inheritance.

Two points remain worth mentioning, although they are tangential to my argument:

First, nowadays traits are all the rage. This is an extension of mixins that doesn't require linear composition. All newer mixin-like systems actually implement traits or at least call them such.

Second, the design rationale for extension methods in Java 8 is not primarily to add mixins, traits, or multiple inheritance but rather to add the ability to retroactively extend existing interfaces to use new methods. It is intended that these extension methods are overridden by implementing classes. Importantly, this allows to update the Collection interface to include methods like the higher-order function map without breaking code that implemented Collection during Java 7 times and thus has no implementation for map.


问:
What are the set of skills that every programmer graduating from college should have?
We had a guest lecturer at our school he went on a tangent regarding those graduating and not being upto the skill level he expects ie. knowledge of one big-time compiled languague like Java, C++ or C#, one scripting language like Python or Ruby, one web framework. What are some other skills that you guys think should be absolutely critical to graduating student?</p>

答:
A passion for programming well

Humility

The ability to learn new things quickly

OwnerDisplayName: Wallz

ContentLicense: CC BY-SA 2.5


问:
Interface Dependencies or Abstract Classes
I have a decision to make and I am wondering what would be the better solution. I am refactoring an older application and intend to really get into the nuts and bolts of it.

There are 8 report types currently and one of the modifications are to allow different reports to be "saved" in different ways. My two thoughts on it were

Have an Abstract Class with an abstract save method, then each report type can define its own way of doing things. Possibly have other abstract classes inheriting from that one, each implementing a virtual Save() method. Then the report classes can inherit from the one with the relevant save mechanism.

Have a report interface, which has a method signature like

```<code>void Save(ISaveMechanism saveMechanism);
</code>```

Then have an interface with a Save() method, then each report type can use saveMechanism.Save(); and just use the concrete implementation required.

Would either solution cause more issues/drawbacks than the other? This project doesn't currently have any associated unit tests but if given time, it would be good to add some later.

答:
I don't think it's an either/or. I think you should use both Interfaces and Abstract Classes.

TL;DR

Abstract Classes

Pros:

Relatively simple

You can provide basic functionality and "hooks" that the subclasses can use.

Cons:

You're "stuck" with the inheritance hierarchy

Client code knows about the Base Class

Interfaces

Pros:

Almost unlimited flexibility

Cons:

Zero implementation provided

May be harder for less experienced coders to understand.

Scenario

Imagine that you create an Abstract Class today. We'll call it BaseReport. BaseReport provides an empty "save" method, and all your current types of reports extend from BaseReport and have their own implementation of save.

For the sake of argument, you also want to display the text of the report before saving it, so your BaseReport extends a simple View component provided by your language of choice that will allow you to put a few text objects and a save button on the screen and not much more. It's really lightweight, so it's a good choice based on all the reports you have in front of you. I'll call it SimpleContainer.

Now, you're nine months down the line, and you need to have a report that has multiple pages, and someone has asked that one of the reports be viewable in either portrait or landscape modes. Neither of these requirements can be fulfilled with a subclass of SimpleContainer.

However, you have a lot of client code that knows about BaseReport, and there might even be a place or two where you've cast to SimpleContainer (where's the harm?). Not only that, the code is more like custom framework code, and you've spawned off four projects that use it. So all of those projects will have to go through QA again if you refactor to go to IReport so you can extend PagedContainer for the one report and RotatableContainer for the other. More than likely, at this point your answer is "sorry, we can't do that." Not because you really can't do that, but because it's too much of a risk to all the other things sitting on top of it.

But for the past 9 months, you've been developing along like gangbusters because you had that base code in BaseReport that allowed you to rip out a new Report type in record time, so you don't want to throw the baby out with the bathwater. Instead, make your BaseReport implement IReport and just make sure that the client code only refers to it as IReport. When the requirement comes in for a PagedContainer, build a BasePagedContainer that implements IReport and then build your individual reports on top.

There's not really a downside to this approach, because the amount of labor it takes to create the interface and implement it into your Abstract Classes is minuscule compared to the amount of flexibility and future-proofing you gain.

And I might have changed a few details to protect the innocent, but the scenario is real, and it happened to me. :)


问:
What does Dependency Injection mean by saying it can inject on runtime?
I understand that the dependency injection is something done by coding and its all done at compile time. And that Dependency injection coding is easily done now by helper tools like Ninject.

However this is at compile time that the dependency injection occurs. Then what does it mean that dependency injection also occurs at Runtime?

This is straight from wiki about Dependency Injection

Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.

I mean I thought about it and came up with the idea that it may refer to multiple interfaces to a single class when a Delegate calls a metho from one of the interfaces, dependency injection decides something like this at runtime, but when I went deeper into it and even discussed it with my boss it sounded like its not that simple as that. And that then, how does the dependency injection makes this decision and assume it the correct one?

Anyone can help me clear out this question?

答:
Dependency injection simply means that you pass in one or more interface implementations, typically to the constructor of the class. The class methods then in turn call methods on these interfaces rather than calling out e.g. to a library directly.

When you do this you can defer the decision about exactly what implementation you want to pass in (inject) until run-time where the decision as to which particular implementation should be used might for instance get configured through a configuration file.


问:
How important are code formatting guidelines?
Coding standards are common in any software development organization, but how important are they to follow?  I can understand the need for some consistency, but when dealing with simple things like the position of braces, line length, etc., I'm not sure excessively strict standards contribute much to software development.

Isn't it more important that your code is readable, not that it conforms to a predefined standard?  It seems they're more like... guidelines anyway.

答:
No matter what language or tool you use, come up with something. Configure your IDE and check in the configuration file.

When anyone checks out the project, they will use the same formatting styles. It does not matter what the style is, only that it is consistent. I have my own preferences with regards to spaces v. tabs, and which line the curly braces go on. But more than my own preferences, I just care that a given source code file agrees with itself. It makes it so much more readable than it being a mishmash resulting from a format war.


问:
Windows Console App vs Service

My Situation

I work for a company that builds software for many other companies.
When I learned installers weren't built-in with VS2012, I was curious how to deploy.
So far, I have just been dropping .exes on our clients servers using PowerShell scripts.
Now I need a full-blown Windows service.

I have seen many example of how to run services via a console application:
https://stackoverflow.com/questions/7764088/net-console-application-as-windows-service

I could easily use sc.exe to create a service based on a console application like this.
I have no idea how Windows would handle Start/Stop/Restart, though.

The Question

This has made me curious what the relationship between console applications and services is in the Window's world. Are services just console applications with hooks to allow the OS to call start and stop? Or are services completely different?

A long time ago, I thought WinForms and console applications were completely different. After messing around in Win32, I realized they were the same thing.

My Hopes

I am hoping services are just console apps, like WinForms, and that I can tap into the Start/Stop capabilities directly in .NET. The built-in installer projects were pretty awful, so I don't feel too bad for copying .exes to the server.

答:
I wouldn't say that a console application is totally different from a windows service.  They are both hosts to execute code.  That being said, there are some key differences:

A service can run even if a user is not logged into the PC.

A service can easily be configured to run in the context of a high-authority accounts such as Network Service or Local System.

A service comes built in with hooks for starting, stopping, restarting, and pausing while running.

A service doesn't have an attached console, it can't print anything to stdout but has to use system logging instead (credit to Martin)

Title: Windows Console App vs Service


答: Your understanding of Dependency Injection is correct and when you do this by coding it will be done at compile time. To have dependencies injected at run time you need Dependency Injection Container (Provider). It basically does the coding for you, you just need to configure it so it can pass the right parameters.

Title: What does Dependency Injection mean by saying it can inject on runtime?

Body:
I understand that the dependency injection is something done by coding and its all done at compile time. And that Dependency injection coding is easily done now by helper tools like Ninject.

However this is at compile time that the dependency injection occurs. Then what does it mean that dependency injection also occurs at Runtime?

This is straight from wiki about Dependency Injection

Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time.

I mean I thought about it and came up with the idea that it may refer to multiple interfaces to a single class when a Delegate calls a metho from one of the interfaces, dependency injection decides something like this at runtime, but when I went deeper into it and even discussed it with my boss it sounded like its not that simple as that. And that then, how does the dependency injection makes this decision and assume it the correct one?

Anyone can help me clear out this question?


答:
Interpersonal and communication skills

Pragmatic approach (not that academical theory)

Ability to think as a client who is not technically-inclined

Ability to evaluate what's important/and what can be disregarded, in terms costs/benefits

Ability to work in a team

Ability to think strategically: architecture, extensibiliy, scalability

Openness to accept that university teachings have little to do with the real world (depends on university - some fare better on this).

Learning process in this profession never ends. One must constantly learn and improve himself, otherwise, he "flunks out" of the game real fast.

Title: What are the set of skills that every programmer graduating from college should have?

Body: We had a guest lecturer at our school he went on a tangent regarding those graduating and not being upto the skill level he expects ie. knowledge of one big-time compiled languague like Java, C++ or C#, one scripting language like Python or Ruby, one web framework. What are some other skills that you guys think should be absolutely critical to graduating student?</p>


答:
I'd suggest following MVC because in the current layout I don't see separation of functionalities in the code. E.g. grouping code in ajax means each file is responsible to fetch and process data (Model), presenting it to client (Controller) and formatting (View).

Edit to clarify if the current layout was already MVC like, it's not clear that it is. Looking at the .php files, you can't tell that .php files in views/ are controllers/models,
but usually when using templates, only .tpl belong in views/. So to fix that, we have
to keep views/*.php together with other .php in ajax/, say in src/.

If you do that, then it'd be clear that you have View in views/ and Model and Controller in src/. Then the next step is to break src/ to models/ and controllers/. This is not as easy as moving files around because you need to break up the files too. E.g. you mention that
the ajax files perform INSERT and UPDATE. Those parts that do that would need to be placed
in separate files and in models/. Once you removed those parts from the original files,
you can put them together as controllers. This is quite rough but should make it clear enough.

So, from your current layout, I'd put and break the php files in controllers/ and model/, put .tpl files in view/ and put all other files that must be accessible by public (.js, .css, etc.) in public/. Also, put 3rd party library in a separate directory, like vendor/.

You might also want to consider using an MVC framework, which most likely will make/suggest a layout for you. Caveat I only wrote to make the php part to be MVC. As you it seems like javascript is used substantially, you can make javascript to be MVC too.

Title: Web application structure review


答:
I haven't used Ninject in a project myself, but I'm familiar with it, so I'll try to use it for an example.

A dependency that is changed at compile-time would be one that is explicitly configured in code which is run at startup of the program. e.g. for the Ninject docs:

```<code>Bind<IWeapon>().To<Sword>();
</code>```

A dependency that is changed at run-time would be one that is configured to use a provider, rather than a concrete type, e.g.

```<code>Bind<IWeapon>().ToProvider(new SwordProvider());
</code>```

Then, the SwordProvider class could provide a CreateInstance() implementation which, say,  hits a database to determine which concrete class to supply. Hence, behaviour could be changed at runtime by updating the database. Or whatever.

Body:
I haven't used Ninject in a project myself, but I'm familiar with it, so I'll try to use it for an example.

A dependency that is changed at compile-time would be one that is explicitly configured in code which is run at startup of the program. e.g. for the Ninject docs:

Bind<IWeapon>().To<Sword>();

A dependency that is changed at run-time would be one that is configured to use a provider, rather than a concrete type, e.g.

Bind<IWeapon>().ToProvider(new SwordProvider());

Then, the SwordProvider class could provide a CreateInstance() implementation which, say,  hits a database to determine which concrete class to supply. Hence, behaviour could be changed at runtime by updating the database. Or whatever.


问:
Schema table for multi-integration tokens
I'm designing a schema table that will manage the auth tokens for integrations // app with social networks.

At the moment only for Twitter and Facebook.

I'm thinking in this mode

```<code>id  social   tw_token   tw_token_auth   tw_secret   tw_secret_key   fb_token  fb_secret
1    twitter   aaa         bbbb           cccc        dddd            NULL       NULL
2    facebook   NULL        NULL          NULL         NULL            AAA1      bbb3
</code>```

I don't like that many NULL, but for a so-simple-schema I would not realize a different table for social networks.

How to perform this better than I'm doing now?

答:
If I understand you correctly, you plan to have a table with a record for each social media account, and one column for each piece of authentication data for each site.

That last part is horribly bad. A schema that has to be changed (by adding columns) whenever a new record is inserted is a really, really bad idea. Either username/password/token or whatever you are using fulfill comparable purposes on different sites. Then they should be in the same column, not in a special-purpose site-specific column. Or they are fundamentally different. Then they need different columns, but it should be the same column for every site that also uses this information. Sites that don't use this particular mechanism can have NULL there. But altogether, there is no reason why you should have more columns than the number of authentication items that the most complex supported site uses.


问:
How much difference does experience make?
I see many job adds which require at least x years experience. The question is how do you know when a candidate has the required years of experience? What do you expect from a person with x years experience (edit: effectively how do you check if the CV isn't lying without relying to skill checking)? What can a person with x years experience can do that one with y years (with y < x) cannot do (edit: assuming they have similar skills)?

There can be cases with some passionate programmer with y years experience that has vast knowledge and worked on multiple projects and other programmer with x years experience (x > y) that has worked on few projects and doesn't have that much experience.

Why can not it be reduced to something like this "if you know this technology and you know how to do that stuff (be it design, communication, estimates etc.) then you are suitable for our job"?

I know you cannot hire a fresh graduate with 1 year experience for the post of an enterprise architect but I also see a problem with the facts that almost all ads ask experience. IMHO firstly passion should be taken into account.

Firstly I did not know if the question is suitable for this site but since there is a tag for recruiting and experience I believe it has a place here.

答:
Your question can be handled by splitting into two sub-questions.

Why use years of experience as a requirement?

Because it's an easily-verifiable metric correlated positively with programming competency. Snagulus's answer already elaborates on the details of correlation, so I'll focus on the "why".

The hard truth is that usually there is more than one candidate for a given position. Also, interviews are quite resource-consuming, especially if they are done "properly", i.e. technical interviews are conducted by technically-competent staff (in this case programmers).

Therefore, some criterion to initially sift through the incoming CVs needs to be used, and preferably one that can be verified by non-technical staff - when in doubt, HR people can always call previous employers and check that yes, John Smith has worked for X years with them.

Why not use "passion" as a requirement instead?

There are at least two problems with this:

how to measure "passion"?

KLOCs logged? Good luck finding that out, also, in programming (and other disciplines), more profuse does not equate to "better".

Open source/hobby projects completed? Not easily checked by HR, and a lot of competent programmers have legitimate reasons to be inactive in that regard - other time-consuming obligations, long work hours with desire to unwind, simple professional fulfillment during work hours etc.

Years of experience? Oh, wait...

is "passion" really a good metric for competence?

As Robert Harvey says in his comment, passion is not really indicative of a competent programming. Compared to experience, it's a mostly orthogonal quality - that is, there exist :

passionate and competent programmers and

dispassionate and technically competent programmers and

passionate and technically incompetent programmers and

passionate and non-technically incompetent programmers,

etc. etc.

The last example is important in our context - years of experience also show that a given programmer has somehow managed to function in his/her job, whereas an dysfunctionally passionate programmer could, e.g. flat-out refuse to participate in even the simplest task management system (say, Scrum Post-it notes), because "it slows me down."

Final disclaimers

First of all, and fortunately, "years of experience" are often evaluated "loosely" - i.e. if you are applying for a job with language X, but only have "commercial" experience with language Y, similar to X, that is also often taken into account.

Secondly, personally I'm not a fan of "N years of experience", and I'm not the only one. There is a simple alternative - specifying "experience in". That usually suffices as a filter, since candidates are forced to document that experience in their CVs - if you get a candidate for a programming position that has previously only done waitering (and this happens!) you know something may be wrong.


答:
The other answers are good, but I would say the #1 overlooked skill in university seems to be actual  software engineering.

The basic classes to teach OOP and a language like Java are great, but in the 3rd and 4th year why are students (at least at my local university) writing compilers and operating systems instead of learning how to identify and create a good architecture, how to dissect requirements and create from that a list of technical specifications, and perhaps most importantly, what the difference is between good code that works and bad code that works.

It's like our universities almost want to churn out coders instead of software engineers.  I would never hire somebody who didn't display some skill/talent in engineering.


答:
However this is at compile time that the dependency injection occurs.

The service type is defined at compile time. This is normally in the form of an interface or a (sometimes abstract) base class. The key point here is Liskovs substitution principle

It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)

So we know the contract of the type at compile time

Then what does it mean that dependency injection also occurs at Runtime?

When implementing DI, for example, using an Inversion of Control container the implementation type is not known until run time.

Let's look at a basic example of making a cup of coffee using Simple Injector as the Inversion of Control container and NUnit to test the code.

Firstly we define the cup and our service type:

```<code>public class Cup
{
    public List<string> ingredients = new List<string>();
}

public interface ICoffeeService
{
    Cup GetCoffee();
}
</code>```

And an implementation of the service:

```<code>public class CoffeeService : ICoffeeService
{
    public Cup GetCoffee()
    {
        Cup cup = new Cup();
        cup.ingredients.Add("Coffee powder");
        cup.ingredients.Add("Hot water");
        return cup;
    }
}
</code>```

Our test method configures the container to return the CoffeeService when asked for an instance of ICoffeeService

```<code>[Test]
public void CoffeeService_GetCoffee_ReturnsCupWithCoffeeAndHotWater()
{
    // Arrange
    var container = new SimpleInjector.Container();
    container.Register<ICoffeeService, CoffeeService>();

    // Act
    var coffeeService = container.GetInstance<ICoffeeService>();
    var cup = coffeeService.GetCoffee();

    // Assert
    Assert.That(cup.ingredients.Count == 2);
    Assert.That(cup.ingredients.Contains("Coffee powder"));
    Assert.That(cup.ingredients.Contains("Hot water"));
}
</code>```

We decide we need to always add cream to our coffee but instead of changing CoffeeService we instead Decorate it with the new feature (Open/Closed principle).

The decorator

```<code>public class AddCreamDecorator : ICoffeeService
{
    private readonly ICoffeeService decorated;

    public AddCreamDecorator(ICoffeeService decorated)
    {
        this.decorated = decorated;
    }

    public Cup GetCoffee()
    {
        Cup cup = this.decorated.GetCoffee();
        cup.ingredients.Add("Cream");
        return cup;
    }
}
</code>```

And the new test

```<code>[Test]
public void DecoratedCoffeeService_GetCoffee_CupWithCoffeeAndHotWaterAndCream()
{
    // Arrange
    var container = new SimpleInjector.Container();
    container.Register<ICoffeeService, CoffeeService>();
    container.RegisterDecorator(typeof(ICoffeeService), typeof(AddCreamDecorator));

    // Act
    var coffeeService = container.GetInstance<ICoffeeService>();
    var cup = coffeeService.GetCoffee();

    // Assert
    Assert.That(cup.ingredients.Count == 3);
    Assert.That(cup.ingredients.Contains("Coffee powder"));
    Assert.That(cup.ingredients.Contains("Hot water"));
    Assert.That(cup.ingredients.Contains("Cream"));
}
</code>```

The most important point to take from this example is that we code to and compile against the service type ICoffeeService and the container gives us the configured runtime implementation. In test one we get an instance of CoffeeService while in test two we get an instance of CoffeeService that is decorated with an instance of AddCreamDecorator - in both cases the caller doesn't care as it get the service it needs.

Body:
However this is at compile time that the dependency injection occurs.

The service type is defined at compile time. This is normally in the form of an interface or a (sometimes abstract) base class. The key point here is Liskovs substitution principle

It states that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)

So we know the contract of the type at compile time

Then what does it mean that dependency injection also occurs at Runtime?

When implementing DI, for example, using an Inversion of Control container the implementation type is not known until run time.

Let's look at a basic example of making a cup of coffee using Simple Injector as the Inversion of Control container and NUnit to test the code.

Firstly we define the cup and our service type:

public class Cup
{
    public List<string> ingredients = new List<string>();
}

public interface ICoffeeService
{
    Cup GetCoffee();
}

And an implementation of the service:

public class CoffeeService : ICoffeeService
{
    public Cup GetCoffee()
    {
        Cup cup = new Cup();
        cup.ingredients.Add("Coffee powder");
        cup.ingredients.Add("Hot water");
        return cup;
    }
}

Our test method configures the container to return the CoffeeService when asked for an instance of ICoffeeService

[Test]
public void CoffeeService_GetCoffee_ReturnsCupWithCoffeeAndHotWater()
{
    // Arrange
    var container = new SimpleInjector.Container();
    container.Register<ICoffeeService, CoffeeService>();

    // Act
    var coffeeService = container.GetInstance<ICoffeeService>();
    var cup = coffeeService.GetCoffee();

    // Assert
    Assert.That(cup.ingredients.Count == 2);
    Assert.That(cup.ingredients.Contains("Coffee powder"));
    Assert.That(cup.ingredients.Contains("Hot water"));
}

We decide we need to always add cream to our coffee but instead of changing CoffeeService we instead Decorate it with the new feature (Open/Closed principle).

The decorator

public class AddCreamDecorator : ICoffeeService
{
    private readonly ICoffeeService decorated;

    public AddCreamDecorator(ICoffeeService decorated)
    {
        this.decorated = decorated;
    }

    public Cup GetCoffee()
    {
        Cup cup = this.decorated.GetCoffee();
        cup.ingredients.Add("Cream");
        return cup;
    }
}

And the new test

[Test]
public void DecoratedCoffeeService_GetCoffee_CupWithCoffeeAndHotWaterAndCream()
{
    // Arrange
    var container = new SimpleInjector.Container();
    container.Register<ICoffeeService, CoffeeService>();
    container.RegisterDecorator(typeof(ICoffeeService), typeof(AddCreamDecorator));

    // Act
    var coffeeService = container.GetInstance<ICoffeeService>();
    var cup = coffeeService.GetCoffee();

    // Assert
    Assert.That(cup.ingredients.Count == 3);
    Assert.That(cup.ingredients.Contains("Coffee powder"));
    Assert.That(cup.ingredients.Contains("Hot water"));
    Assert.That(cup.ingredients.Contains("Cream"));
}

The most important point to take from this example is that we code to and compile against the service type ICoffeeService and the container gives us the configured runtime implementation. In test one we get an instance of CoffeeService while in test two we get an instance of CoffeeService that is decorated with an instance of AddCreamDecorator - in both cases the caller doesn't care as it get the service it needs.


问:
Do you know of a data-pump design pattern?
I frequently encounter a situation where I need to write a program which reads data-objects from a file or system, does a transformation on the data, convert the data to another datamodel and then push the data in another file, or system.
Do you know of a object-model which facilitates these type of programs in such a way that it is pluggable and scalable?  </p>

答: here's a link to an article on an alleged Extract/Transform/Load (ETL) design pattern but it sounds like what you want is a framework</p>


问:
Macro vs. Static functions in Header
for a lot of quick tasks where one could employ a function f(x,y), in plain C, macros are used. I would like to ask specifically about these cases, that are solvable by a function call (i.e. macros used for inlining functions, not for code expansion of arbitrary code).

Typically C functions are not inlined since they might be linked to from other C files. However, static C functions are only visible from within the C file they are defined in. Therefore they can be inlined by compilers. I have heard that a lot of macros should be replaced by turning them into static functions, because this produces safer code.

Are there cases where this is a not good idea?

Again: Not asking about Code-Production macros with ## alike constructs that cannot at all be expressed as a function.

答:
Macros  that are solvable by a function call have a lot of pitfalls:

They are hard to write, because you may have to handle properly arguments like ++i.

They are hard to debug with a visual debugger since you cannot step through a macro
or put a breakpoint there.

They are hard to handle correctly when analysing compilations dependencies.

Macros that are solvable by a function call could have been useful to provide inlining in a primitive compiler.  I am not aware of any compiler not handling inline functions and some can even inline across compilation units.

Typically C functions are not inlined since they might be linked to from other C files.

There is no reason why a compiler would not be able to provide two versions of a function, a traditional called one and an inlined one.  You should look at the documentation of the compiler you are targetting.  Also, you may want to look at generated assembly: even if you do not know assembly, you can quickly learn to tell if some function has been inlined or not. (Start with baby-examples to quickly learn this.)

Title: Macro vs. Static functions in Header


问:
When to write software project documentation on code
I usually write my software projects in Java, and I am still a bit confused as to when to document my classes, interfaces and methods.

There are two ways:

1) Write documentation after declaring or coding a class/interface/method/constructor. This way I am sure documentation is handled immediately.

Disadvantage: I might modify the arguments of a method/constructor or I might modify the functionality of the class or interface and forget to edit the documentation.

2) Write documentation after finishing the project (or a major finish/version of the project), this way I am sure to document the full functionality/arguments of methods/constructors as well as documenting all exceptions thrown.

Disadvantage: It usually becomes another great overwhelming task to go through hundreds of classes and methods at the end of the project, trying to write documentation code.

As you can see both scenarios have their disadvantages but I think one is more advantageous than the other. I am puzzled as to which. Also I am not implying this to Java alone, it can be applied to any programming language that requires documentation.

答:
"this way I am sure to document the full functionality"

You should not document the functionality but the contract the API which your method forms. i.e. what parameters it expects and what returns to the caller (+Exceptions it may throw).
The functionalit (inner details) should not be the business of the caller context. But if that is the case, your method makes use of side effects and that is a deadly antipattern.

Anyways, I would suggest immidiate documentation: parameters, returned stuff, exceptions, nothing else.

ContentLicense: CC BY-SA 4.0


答:
Actually I suggest writing a the documentation of a class or function immediately before starting to implement it to get yourself a clear vision of what the requirements and responsibilities of that function or class are. Proof-read the docs after you have a version of your function or class ready, and proof-read it again when you change something. Make the docs complete at every code-review (you do code reviews, don't you?).

And think also about "do I really need that comment, or can I make the function or class names, parameter names etc more self- describing?" Eliminating unnecessary docs is IMHO the most important key for keeping docs and code in sync.

Title: When to write software project documentation on code

Body:
I usually write my software projects in Java, and I am still a bit confused as to when to document my classes, interfaces and methods.

There are two ways:

1) Write documentation after declaring or coding a class/interface/method/constructor. This way I am sure documentation is handled immediately.

Disadvantage: I might modify the arguments of a method/constructor or I might modify the functionality of the class or interface and forget to edit the documentation.

2) Write documentation after finishing the project (or a major finish/version of the project), this way I am sure to document the full functionality/arguments of methods/constructors as well as documenting all exceptions thrown.

Disadvantage: It usually becomes another great overwhelming task to go through hundreds of classes and methods at the end of the project, trying to write documentation code.

As you can see both scenarios have their disadvantages but I think one is more advantageous than the other. I am puzzled as to which. Also I am not implying this to Java alone, it can be applied to any programming language that requires documentation.


答:
There is no universal standard for what a team should or shouldn't do. Some teams need to follow strict guidelines, some don't.

The point is, you should work together as a team and decide what is best for your team. Code should be easy to read, because it is read orders of magnitudes more times than it is written. If your team needs guidance to create readable code, stick to a coding standard. If you don't, don't.

All that being said, I think most teams would benefit from agreeing on a standard way to name variables, functions and classes, position braces, and so on. If the team can't agree on something as simple as that, how can they expect to come together and make the really important decisions? Plus, your team won't be made up of the same people forever -- people leave, new people are hired. The easier it is for new people to grok the codebase, the quicker they can contribute to the team without lowering the quality of the code.

Title: How important are code formatting guidelines?

Body:
Coding standards are common in any software development organization, but how important are they to follow?  I can understand the need for some consistency, but when dealing with simple things like the position of braces, line length, etc., I'm not sure excessively strict standards contribute much to software development.

Isn't it more important that your code is readable, not that it conforms to a predefined standard?  It seems they're more like... guidelines anyway.


问:
Should I start a project I am hoping to recruit others to?
I have an idea for a program that I think is a good one (Don't we all?).  I am an amateur programmer and would like to recruit some more advanced programmers onto the project since there are some aspects that I am not skilled enough to do myself.  Is it better to

a) Develop the software on my own as much as I can, even though it will be amateurish, and then show a demo to potential recruits

or

b) Try and recruit some more advanced programmers and seek their advice and guidance before I get started so that it is done correctly from the beginning?

I would especially love it if someone has any experience of being in a similar position, but sage speculation is welcome too.

答:
Can you explain why a skilled programmer would want to implement your idea for fun, when I am sure they have plenty of their own to implement?

I have been programming for around 25 years, ( I started early) but as I have explained to my employers over the years I do the programming for free.  The reason why they pay me is to tell me what to program, to insist that I turn up to the office, to follow a certain dress code etc...

Now, if you put together the proof of concept demo, show it around, have someone approach you looking for an investment and then start looking for a technical architect - then you are able to pay someone to take your idea and turn it into a product.


问:
How is it called when you define constants that simply refer to a large namespace?
I am using JRuby.

I have many classes implemented in Java, and I want to create objects off of them in my Ruby scripts.

Suppose that I have a class Sprite in Java. In Ruby, to refer to it, I use the following:

```<code>Java::ComMyWebsiteMyProjectName::Sprite
</code>```

Because Sprite is defined in the package com.myWebsite.myProjectName.

Now then, to simplify things, I like to do this:

```<code>Sprite = Java::ComMyWebsiteMyProjectName::Sprite
</code>```

Which sets the constant Sprite to the Sprite class defined in Java. Now my Ruby code can refer to it by just writing Sprite.

I have a file full of that kind of declarations. Something like:

```<code>Sprite   = Java::ComMyWebsiteMyProjectName::Sprite
Texture  = Java::ComMyWebsiteMyProjectName::Texture
Bitmap   = Java::ComMyWebsiteMyProjectName::Bitmap
Math     = Java::ComMyWebsiteMyProjectName::Math
Geometry = Java::ComMyWebsiteMyProjectName::Geometry
</code>```

Now, I am not exactly very familiar with programming concepts. I am having problems giving this file a name, because I don't even know if there is a name for this kind of thing. Does this kind of "practice" have an actual name?

答: Generically, this sort of thing is called Type Aliasing. When you're doing it specifically for a namespace, you're importing the namespace (or more accurately, importing the types within the namespace).


答: This is usually called "bindings". For example, there are many node.js modules that are just bindings with C++ libraries. Or Python libraries that provide bindings for C code. And there are probably some JRuby libraries that provide bindings for Java code.</p>

Title: How is it called when you define constants that simply refer to a large namespace?

Body:
I am using JRuby.

I have many classes implemented in Java, and I want to create objects off of them in my Ruby scripts.

Suppose that I have a class Sprite in Java. In Ruby, to refer to it, I use the following:

```<code>Java::ComMyWebsiteMyProjectName::Sprite
</code>```

Because Sprite is defined in the package com.myWebsite.myProjectName.

Now then, to simplify things, I like to do this:

```<code>Sprite = Java::ComMyWebsiteMyProjectName::Sprite
</code>```

Which sets the constant Sprite to the Sprite class defined in Java. Now my Ruby code can refer to it by just writing Sprite.

I have a file full of that kind of declarations. Something like:

```<code>Sprite   = Java::ComMyWebsiteMyProjectName::Sprite
Texture  = Java::ComMyWebsiteMyProjectName::Texture
Bitmap   = Java::ComMyWebsiteMyProjectName::Bitmap
Math     = Java::ComMyWebsiteMyProjectName::Math
Geometry = Java::ComMyWebsiteMyProjectName::Geometry
</code>```

Now, I am not exactly very familiar with programming concepts. I am having problems giving this file a name, because I don't even know if there is a name for this kind of thing. Does this kind of "practice" have an actual name?


问:
Software license for a publicly funded institution
This is probably something that should go to the legal department -- presuming they have any inklings about software licensing -- but what software license should I use against code developed for use at a publicly funded institution (in the UK)?

Specifically, it's internal-use code for various university systems. I believe it should be open source -- and feel that the MIT license would be most appropriate -- but I have a feeling that certain proprietary procedures and policies, that might be revealed by the code, may be restricted. ("May" in italics, because I'm not 100% sure: As a publicly funded body, I am under the impression that anything that doesn't conflict with the Data Protection Act 1998 should be made available under the Freedom of Information Act 2000.)

This is largely moot, because the source won't be published publicly. (Although, presumably, if anyone requests it, then that's allowed; providing sensitive information is redacted.) However, I'm interested to hear others' thoughts on the matter.

答:
The owner of the copyright to the source code is the one who must make the decision on how to license the code, if any license is going to be provided.

You have a number of misconceptions behind your question.

As a publicly funded body, I am under the impression that anything that doesn't conflict with the Data Protection Act 1998 should be made available under the Freedom of Information Act 2000.)

First off, I think it's a stretch to consider source code as data.  Source code is compiled into instructions that operate upon data.  The source code executes and enforces the school's operating procedures.

Second, there are a number of exceptions within the FIA that you reference.  You already cited one potential restriction within the code that would prevent disclosure, but there may be many more.

Third, the FIA is based upon citizens requesting information.  I think it's a stretch to say that the FIA prompts you to preemptively release that information.

Fourth, FIA enables transparency so that the citizenry may review the actions of the government and other public bodies.  The FIA does not provide a license for the reviewer to then re-use that information in any way that they see fit.

I believe it should be open source -- and feel that the MIT license would be most appropriate

MIT license essentially gives away the source code for free and allows the recipient to do whatever they wish with it.  Even if the source code is subject to the DPA and FIA, it's a really big stretch to say that the code should just be given away freely for anyone to do whatever with.

This is largely moot, because the source won't be published publicly.

Then why are you licensing the software?  A software license allows the copyright owner to grant permissions (a license) to a user of the software (licensee).  If the software won't be published, then others can't access the software and would not be able to utilize the permissions (license) that had been granted.

This is probably something that should go to the legal department

Yes, as a matter of fact it should.  Because the legal department represents the legal interests of the University, which is the copyright holder.  As an employee of the University, you are not the copyright owner of that source.  Therefore this is not your decision to make.  It's their decision to make, which is the function of their legal department.

presuming they have any inklings about software licensing

Is a moot point.  Courts have consistently upheld that a property (copyright) owner does not need to have a full understanding of all of the ramifications in order to make decisions about their property.  The fact that you don't believe they understand what's involved is irrelevant to who should make the decision and whether their decision is binding.

but what software license should I use against code developed for use at a publicly funded institution

Unless the legal department tells you otherwise, you shouldn't be putting a license on the code.  You could put a copyright statement in the code indicating that all rights are reserved and the copyright belongs to the University.  However, the Berne convention considers the equivalent of that to be the default copyright statement and states that you are not required to put a copyright statement in place.  You may, and it's probably better if you do in order to make things clear, but you're not obligated to.

With all that having been said, kudos to you for thinking through this issue and asking before you published the code.  In theory, if you had publicly published the code then you could have been reprimanded for releasing University property.

You do have some valid questions that the legal department should answer for you, but please realize that Intellectual Property can be a fairly complex legal field with a huge number of exceptions based upon the jurisdiction.

The best thing for you to do at this point is to contact your legal department and ask them how they want the copyright for the code to be indicated.  Also ask if they want a license applied to the code and bear in mind that the code need not be licensed at all.


问:
Moving business logic from services to classes?
I have a Grails application with a number of services that are starting to get very large.

The flow in the majority of my service methods is

Database read (Returns DBCursor from MongoDB)

Iterate through the cursor and perform some operations.

Return results from operation.

I'm beginning to  consider moving the logic in Step 2 out to Groovy classes in order to clean up my code base and allow for unit testing. However reading some guidelines they state that the majority of the logic should go in services.

Is moving this logic out to Groovy classes going aghainst best practices?

答: Usually that type of guideline (that the majority of the logic should go in services) means that your business logic should be accessible through services rather than e.g. in an MVC controller. A service should be the interface to some business logic, but all the code implementing that business logic doesn't necessarily have to live in a service class.


问:
Why do most programming languages only support returning a single value from a function?
Is there a reason why functions in most(?) programming languages are designed to support any number of input parameters but only one return value?

In most languages, it is possible to "work around" that limitation, e.g. by using out-parameters, returning pointers or by defining/returning structs/classes. But it seems strange that programming languages were not designed to support multiple return values in a more "natural" way.

Is there an explanation for this?

答:
The real reason that a single return value is so popular is the expressions that are used in so many languages. In any language where you can have an expression like x + 1 you are already thinking in terms of single return values because you evaluate an expression in your head by breaking it up into pieces and deciding the value of each piece. You look at x and decide that it's value is 3 (for example), and you look at 1 and then you look at x + 1 and put it all together to decide that the value of the whole is 4. Each syntactic part of the expression has one value, not any other number of values; that is the natural semantics of expressions that everyone expects. Even when a function returns a pair of values it's still really returning one value that's doing the job of two values, because the idea of a function that returns two values that aren't somehow wrapped up into a single collection is too weird.

People don't want to deal with the alternative semantics that would be required to have functions return more than one value. For example, in a stack-based language like Forth you can have any number of return values because each function simply modifies the top of the stack, popping inputs and pushing outputs at will. That's why Forth doesn't have the sort of expressions that normal languages have.

Perl is another language that can sometimes act like functions are returning multiple values, even though it's usually just considered returning a list. The way lists "interpolate" in Perl gives us lists like (1, foo(), 3) which might have 3 elements as most people who don't know Perl would expect, but could just as easily have only 2 elements, 4 elements, or any greater number of elements depending on foo(). Lists in Perl are flattened so that a syntactic list doesn't always have the semantics of a list; it can be merely a piece of a larger list.

Another way to have functions return multiple values would be to have an alternative expression semantics where any expression can have multiple values and each value represents a possibility. Take x + 1 again, but this time imagine that x has two values {3, 4}, then the values of x + 1 would be {4, 5}, and the values of x + x would be {6, 8}, or maybe {6, 7, 8}, depending on whether one evaluation is allowed to use multiple values for x. A language like that might be implemented using backtracking much like Prolog uses to give multiple answers to a query.

In short, a function call is a single syntactic unit and a single syntactic unit has a single value in the expression semantics that we all know and love. Any other semantics would force you into weird ways of doing things, like Perl, Prolog, or Forth.


答:
Years experience is simply a filter that gives a "rough" estimate about what is expected of the person utilizing the desired skills listed in the job description.

Here's prettty much what I would expect, but others may have different ideas:

2 years or less - You should be able to do specific tasks that you are told to do, with employers knowing that there will be a learning curve with a fair amount of supervision for most of those tasks.

3 - 5 years - You should be able to do the tasks you are told to do, without much hand-holding because you should already have done similar tasks in your 0 to 2 years experience. You should also be starting to show some "smart" initiative and be able to handle smaller tasks that aren't necessarily clearly defined. (e.g. Be able to design modules from the requirements, where you have to track some of those requirements down yourself).

5 - 7 years - You should be able to work on your own and be able to decide what those "tasks" from above are. You should be able to handle mid-sized tasks that aren't clearly defined. (e.g. Be able to design/implement/selloff subsystems). You should also be starting to lead subsystem teams in this time-range. Give necessary presentations of subsystems they are responsible for, to at least the internal team.

8 - 10 years - Can be relied upon to be given very large and/or the critical subsystems of the project. Resident expert in several technologies. Can lead large subsystem teams. Give presentations of the subsystems they are responsible for to the customer.

10+ years - Can handle pretty much any software task thrown at them, within the confines of the job description AND most other semi-related software tasks. Resident expert in a large number of software areas. Can lead large projects, from requirements through selloff. Understands system design and not just module/subsystem design. Is able to design reliable, robust and maintainable systems. Is the software interface to the customer, including presentations from a systems perspective. Can adequately put together bid proposals and schedules.

While the years of experience definition is vague, it is not only for the employer's benefit but it is also a guide to the job-seeker.  Thus, if you get hired, claiming you have 8 to 10 years experience and come on the job and need to be told every little task you need to do then at best your future at the company is "very limited" if you even last very long at all. First impressions are hard to change, so even if you get better as a developer, people will still likely maintain their original impression of you.

I've seen a fair number of "senior" developers get hired that were gone in a matter of months or in a couple of years were put on the "employee development" program, which is really just the fast track to being the first on the layoff list. If those same developers had come in at a lower level (of course that means lower pay) then they very well may have been considered a successful hire and seen as performing adequately.

Title: How much difference does experience make?

Body:
I see many job adds which require at least x years experience. The question is how do you know when a candidate has the required years of experience? What do you expect from a person with x years experience (edit: effectively how do you check if the CV isn't lying without relying to skill checking)? What can a person with x years experience can do that one with y years (with y < x) cannot do (edit: assuming they have similar skills)?

There can be cases with some passionate programmer with y years experience that has vast knowledge and worked on multiple projects and other programmer with x years experience (x > y) that has worked on few projects and doesn't have that much experience.

Why can not it be reduced to something like this "if you know this technology and you know how to do that stuff (be it design, communication, estimates etc.) then you are suitable for our job"?

I know you cannot hire a fresh graduate with 1 year experience for the post of an enterprise architect but I also see a problem with the facts that almost all ads ask experience. IMHO firstly passion should be taken into account.

Firstly I did not know if the question is suitable for this site but since there is a tag for recruiting and experience I believe it has a place here.


答:
Read Enterprise Application Integration Patterns.

There is a website related to it here that contains a wealth of inter-application processing design patterns for you to browse. In particular, I'd draw your attention to these patterns:

Messaging
How can I integrate multiple applications so that they work together and can exchange information?

Message Channel
How does one application communicate with another using messaging?

Message Router
How can you decouple individual processing steps so that messages can be passed to different filters depending on a set of conditions?

I've got a copy of the book myself and it's packed with detail about inter-application and inter-system design patterns.

Title: Do you know of a data-pump design pattern?

Body:
I frequently encounter a situation where I need to write a program which reads data-objects from a file or system, does a transformation on the data, convert the data to another datamodel and then push the data in another file, or system.
Do you know of a object-model which facilitates these type of programs in such a way that it is pluggable and scalable?  </p>


问:
How Stack and Heap is allocated for threads under the same process in Windows?
Stack for different thread is different.but what about Heap. If Heap is different for different threads, then how they share objects?</p>

答: The standard implementation for operating system threads is that they share the same memory (i.e. heap), code, data, resource handles etc.  Code using this kind of threading can share objects (although you should then be asking "How do they share objects safely?").  However, some languages (e.g. Erlang) offer their own version of threads which do not have access to shared memory.  In such cases, there is no shared state and therefore no shared objects; these constructs communicate by some form of message passing.


问:
Would using rainbow tables to detect weak user passwords feasible?
As I understand in most security breach where the list of hashed password are compromised, attackers do use brute-force to try to find weak password and, invariably, they always find quite some (like in the recent Github breach).

If I'm not mistaken in most cases when a user creates an account, the password is sent, encrypted (due to TLS / SSL), to the website which then adds some salt and stores the hash + salt.

Even in most sophisticated cases (like when bcrypt is used), upon account creation there's one point in time at which the server does have the password in cleartext.

My question is: couldn't you use, at that very moment when you have the password in the clear that the user is trying to use for his new account, a gigantic rainbow-table on the server side to check for billions and billions of weak passwords in a split-nanosecond?

Then if you detect that a weak password is used, you'd simply tell to the user that his password is too simple and that, no, using "edcrfvtgb1" isn't smart.

I mean: if attackers manage to brute-force weak-password even though they have to deal with the problem of the salt, couldn't servers benefit from the fact that, when the users creates a new account, they do know the password in the clear to simply look it up in a big rainbow table when the user creates his account?

This doesn't seem hard to implement and seen harddisk sizes these days, it's probably not problematic to store a big rainbow table on the server side.

Am I missing something obvious or would this help catch a lot of weak passwords and, hence, mitigate the endless accounts compromise we keep seeing on a nearly daily basis?

答:
The lookup time would be negligible, so this is a feasible way to prevent the use of weak passwords. However as @thorsten mentions in his comment, if you're implementing this on top of other password content requirements and some user enters a password that meets those requirements but is also in your table, it would be difficult to describe to the user exactly what was wrong with the password in a way that's easy for anyone to understand.

As @Mike eluded to in a comment, this type of security measure wouldn't be implemented with a rainbow table (which as he said is a map of hashes to plaintext strings), it would be implemented with a simple list of weak passwords. You don't need the hashes in this case.


问:
Confusion with gpl license
I am really confused about software linceses, I've read a lot of articles but I can't find an answer to my question, which is:
Can I develop and sell applications that uses libraries under gpl license? Like for instance, I want to use agsXMPP library in a windows phone app, and sell it in the market, so is it legal?</p>

答:
Stop reading articles, and read the actual GPL itself.  It's not that hard.

Yes, you can sell applications.  But if someone who receives an application asks for it, then you have to give them all the source code for anything that includes code licenced under the GPL.

Title: Confusion with gpl license


问:
Naming convention for higher order functions?
Is there a naming convention for higher order functions? That is, functions which return other functions.

An example in Javascript:

```<code>function onlyDivisibleBy(div) { // <-- higher order function
  return function (n) {
    return n % div === 0;
  }
}

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

arr.filter(onlyDivisibleBy(3)); // [0, 3, 6, 9]
arr.filter(onlyDivisibleBy(5)); // [0, 5]
</code>```

I've tended to write it as above: that is, optimising for legibility at the invocation point (I'd read the last lines above as "filter the array to get items only divisible by 5"), however at the definition point away from the context in which it's used, it's not so easy to understand what this function does from its name.

答:
In strongly typed functional languages, it is obvious from the function signature what is a higher-order function and what is not, so there is simply no need.

In other languages, I've never come across such a naming convention and I can't think of one which wouldn't just be cumbersome.  Better to concentrate on naming functions well than to overload the names like that, I think.


答:
No, and you should not use any.

Why?

Because that would be a kind of Hungarian notation. The idea is exactly that functions passed to higher-order functions are just a kind of variables. So treat them like that.

Title: Naming convention for higher order functions?

Body:
Is there a naming convention for higher order functions? That is, functions which return other functions.

An example in Javascript:

```<code>function onlyDivisibleBy(div) { // <-- higher order function
  return function (n) {
    return n % div === 0;
  }
}

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

arr.filter(onlyDivisibleBy(3)); // [0, 3, 6, 9]
arr.filter(onlyDivisibleBy(5)); // [0, 5]
</code>```

I've tended to write it as above: that is, optimising for legibility at the invocation point (I'd read the last lines above as "filter the array to get items only divisible by 5"), however at the definition point away from the context in which it's used, it's not so easy to understand what this function does from its name.


答:
No, I don't think you need a special naming convention to indicate you are returning a function. As we can see from languages where functions are curried, returning a function is essentially the same as having a function with multiple arguments. e.g. there is little difference between onlyDivisibleBy(3)(6) and onlyDivisibleBy(3,6)

I would change the name from onlyDivisibleBy to isDivisibleBy though as I think is is a more common way to indicate a predicate and onlyDivisibleBy(3)(6) seems odd to return true given that 6 clearly also is divisible by 2


问:
Is it okay to test multiple similar files in one functional test
I've a functional test using Junit which tests delivery of xml file to an end-point. XML file is sent by client, so I copied it to a test folder, read it from there in my test and do asserts.

We have 10-20 such files with different data but same format, my architect wants me to copy all of them into same folder, loop through them in same test, just to make sure that they are delivered successfully. Note, I am not testing any data validations in this test just successful delivery.

I am not sure if its a good idea to loop through multiple files in a single test in my case because if one fails rest will not be executed and also not convinced for writing 20 tests doing exactly same thing. Please advice

答:
If the goal of the test is to determine whether the method under test will deliver all 20 files, then it is a single test, and should be written accordingly.

I'm not sure it would buy you much to split it into 20 separate tests, since you're testing the same functionality in each one.


问:
How to safeguard a REST API for only trusted mobile applications
How do I make sure my REST API only responds to requests generated by trusted clients, in my case my own mobile applications? I want to prevent unwanted requests coming from other sources. I don't want users to fill in a serial key or whatever, it should happen behind the scenes, upon installation, and without any user interaction required.

As far as I know, HTTPS is only to validate the server you are communicating with is who it says it is. I'm ofcourse going to be using HTTPS to encrypt the data.

Is there a way to accomplish this?

Update:
The user can perform read-only actions, which do not require the user to be logged in, but they can also perform write actions, which do require the user to be logged in (Authentication by Access Token). In both cases I want the API to respond to requests coming only from trusted mobile applications.

The API will also be used for registering a new account through the mobile application.

Update 2: It seems like there are multiple answers to this, but I honestly don't know which one to flag as the answer. Some say it can be done, some say it can't.

答:
SSL will secure the communication channel.

Successful login will issue an authentication token over encrypted connection.

Authentication token will be passed to your REST API in all the subsequent requests.


答:
How you should write this test is more a matter of style than anything else.

Some say that each test method should have only a single assertion, because that makes the test very focused, and it's easy to quickly tell exactly what was wrong.

This seems too extreme to me, so you could follow the guidance of your architect but make the error message in your assertion clear as to which file caused the test failure.

Even better, to have all files tested even when one fails, don't use assertions on a per-file basis. Cache each file's result in the execution loop and if any failed, output the details and fail the test. For example:

```<code>@Test
public void testAllFiles() {
    final Set<String> failures = new HashSet<>();
    for (File file : getAllFiles()) {
        final Boolean success = processFile(file); // or however you determine success/failure
        if (!success) failures.add(file.getName());
    }

    if (!failures.isEmpty()) {
        log.error("Failed file(s):");
        for (String filename : failures) {
            log.error("\t"+filename);
        }
        fail();
    }
}
</code>```

Title: Is it okay to test multiple similar files in one functional test

Body:
I've a functional test using Junit which tests delivery of xml file to an end-point. XML file is sent by client, so I copied it to a test folder, read it from there in my test and do asserts.

We have 10-20 such files with different data but same format, my architect wants me to copy all of them into same folder, loop through them in same test, just to make sure that they are delivered successfully. Note, I am not testing any data validations in this test just successful delivery.

I am not sure if its a good idea to loop through multiple files in a single test in my case because if one fails rest will not be executed and also not convinced for writing 20 tests doing exactly same thing. Please advice

Body:
How you should write this test is more a matter of style than anything else.

Some say that each test method should have only a single assertion, because that makes the test very focused, and it's easy to quickly tell exactly what was wrong.

This seems too extreme to me, so you could follow the guidance of your architect but make the error message in your assertion clear as to which file caused the test failure.

Even better, to have all files tested even when one fails, don't use assertions on a per-file basis. Cache each file's result in the execution loop and if any failed, output the details and fail the test. For example:

@Test
public void testAllFiles() {
    final Set<String> failures = new HashSet<>();
    for (File file : getAllFiles()) {
        final Boolean success = processFile(file); // or however you determine success/failure
        if (!success) failures.add(file.getName());
    }

    if (!failures.isEmpty()) {
        log.error("Failed file(s):");
        for (String filename : failures) {
            log.error("\t"+filename);
        }
        fail();
    }
}


答:
For a test to check that all files are delivered use the answer of Robert Harvey.

If you need to run a test with 20 different inputs use a data provider. Don't create loops in the code but use the loops structure with data providers so you have less code and use a standard solution for the issue.


答:
You Can't.

You can never verify an entity, any entity, be it a person, hardware client or software client. You can only verify that what they are telling you is correct, then assume honesty.

For example, how does Google know it is I'm logging into my Gmail account? They simply ask me for a user name and password, verify that, then  assume honesty because who else would have that info? At some point Google decided that this was not enough and added behavioral verification (looking for odd behavior) but that is still relying on the person to do the behavior, then validating the behavior.

This is exactly the same thing with validating the Client. You can only validate the behavior of the Client, but not the Client itself.

So with SSL, you can verify the Client has a valid cert or not, So one can simply install your App, get the Cert, then run all new code.

So the question is: Why is this so critical? If this is a real concern, I would question your choice of a fat client. Perhaps you should go with a web App (so you don't have to expose your API).

Also see: Defeating SSL Certificate Validation for Android Applications

and : How safe are client SSL certificates in a mobile app?

Title: How to safeguard a REST API for only trusted mobile applications

Body:
How do I make sure my REST API only responds to requests generated by trusted clients, in my case my own mobile applications? I want to prevent unwanted requests coming from other sources. I don't want users to fill in a serial key or whatever, it should happen behind the scenes, upon installation, and without any user interaction required.

As far as I know, HTTPS is only to validate the server you are communicating with is who it says it is. I'm ofcourse going to be using HTTPS to encrypt the data.

Is there a way to accomplish this?

Update:
The user can perform read-only actions, which do not require the user to be logged in, but they can also perform write actions, which do require the user to be logged in (Authentication by Access Token). In both cases I want the API to respond to requests coming only from trusted mobile applications.

The API will also be used for registering a new account through the mobile application.

Update 2: It seems like there are multiple answers to this, but I honestly don't know which one to flag as the answer. Some say it can be done, some say it can't.


答: It would not be too secure, but you could add some kind of secret code or even a dgital signature. Downside: It must be included in the app, which makes it easy to obtain it if you know what you do.</p>


问:
What is the difference between self-types and trait inheritance in Scala?
When Googled, many responses for this topic come up. However, I don't feel like any of them do a good job of illustrating the difference between these two features. So I'd like to try one more time, specifically...

What is something that can be done with self-types and not with inheritance, and vice-versa?

To me, there should be some quantifiable, physical difference between the two, otherwise they are just nominally different.

If Trait A extends B or self-types B, don't they both illustrate that being of B is a requirement? Where is the difference?

答:
If trait A extends B, then mixing in A gives you precisely B plus whatever A adds or extends.  In contrast, if trait A has a self reference which is explicitly typed as B, then the ultimate parent class must also mix in B or a descendant type of B (and mix it in first, which is important).

That's the most important difference.  In the first case, the precise type of B is crystallised at the point A extends it.  In the second, the designer of the parent class gets to decide which version of B is used, at the point where the parent class is composed.

Another difference is where A and B provides methods of the same name.  Where A extends B, A's method overrides B's.  Where A is mixed in after B, A's method simply wins.

The typed self reference gives you much more freedom; the coupling between A and B is loose.

UPDATE:

Since you're not clear about the benefit of these differences...

If you use direct inheritance, then you create trait A which is B+A.  You have set the relationship in stone.

If you use a typed self reference, then anybody who wants to use your trait A in class C could

Mix B and then A into C.

Mix a subtype of B and then A into C.

Mix A into C, where C is a subclass of B.

And this is not the limit of their options, given the way Scala allows you to instantiate a trait directly with a code block as its constructor.

As for the difference between A's method winning, because A is mixed in last, compared to A extending B, consider this...

Where you mix in a sequence of traits, whenever method foo() is invoked, the compiler goes to the last trait mixed in to look for foo(), then (if not found), it traverses the sequence to the left until it finds a trait which implements foo() and uses that.  A also has the option to call super.foo(), which also traverses the sequence to the left till it finds an implementation, and so on.

So if A has a typed self reference to B and the writer of A knows that B implements foo(), A can call super.foo() knowing that if nothing else provides foo(), B will.  However, the creator of class C has the option to drop any other trait in which implements foo(), and A will get that instead.

Again, this is much more powerful and less limiting than A extending B and directly calling B's version of foo().


问:
Static factory vs factory as a singleton
In some of my code, I have a static factory similar to this:

```<code>public class SomeFactory {

    // Static class
    private SomeFactory() {...}

    public static Foo createFoo() {...}

    public static Foo createFooerFoo() {...}
}
</code>```

During a code review, it was proposed that this should be a singleton and injected.  So, it should look like this:

```<code>public class SomeFactory {

    public SomeFactory() {}

    public Foo createFoo() {...}

    public Foo createFooerFoo() {...}
}
</code>```

A few things to highlight:

Both factories are stateless.

The only difference between the methods are their scopes (instance vs static).  The implementations are the same.

Foo is a bean that does not have an interface.

The arguments I had for going static was:

The class is stateless, therefore doesn't need to be instantiated

It seems more natural to be able to call a static method than to have to instantiate a factory

The arguments for the factory as a singleton was:

Its good to inject everything

Despite the statelessness of the factory, testing is easier with injection (easy to mock)

It should be mocked when testing the consumer

I have some serious issues with the singleton approach since it seems to suggest that no methods should ever be static.  It also seems to suggest that utilities such as StringUtils should be wrapped and injected, which seems silly.  Lastly, it implies that I'll need to mock the factory at some point, which doesn't seem right.  I can't think of when I'd need to mock the factory.

What does the community think?  While I don't like the singleton approach, I don't seem to have a terribly strong argument against it.

答:
Just off the top of my head, here are some of the problems with statics in Java:

static methods don't play by the OOP "rules".  You can't force a class to implement specific static methods (as far as I know).  So you can't have multiple classes implementing the same set of static methods with the same signatures.  So you're stuck with one of whatever it is you're doing.  You can't really subclass a static class, either.  So no polymorphism, etc.

since methods aren't objects, static methods can't be passed around and they can't be used (without doing a ton of boilerplate coding), except by code that is hard-linked to them -- which makes the client code highly coupled.  (To be fair, this isn't solely the fault of statics).

statics fields are pretty similar to globals

You mentioned:

I have some serious issues with the singleton approach since it seems to suggest that no methods should ever be static. It also seems to suggest that utilities such as StringUtils should be wrapped and injected, which seems silly. Lastly, it implies that I'll need to mock the factory at some point, which doesn't seem right. I can't think of when I'd need to mock the factory.

Which makes me curious to ask you:

what, in your opinion, are the advantages of static methods?

do you believe that StringUtils is correctly designed and implemented?

why do you think you'll never need to mock the factory?