问:
Understanding the static keyword
I have some experience in developing with Java, Javascript and PHP.

I am reading Microsoft Visual C# 2010 Step by Step which I feel it is a very good book on introducing you to the C# language.

I seem to be having problems in understanding the static keyword. From what I understand this far if a class is declared static all methods and variable have to be static. The main method always is a static method so in the class that the main method exists all variables and methods are declared static if you have to call them in the main method. Also I have noticed that in order to call a static method from another class you do not need to create an object of that you can use the class name.

But what is the actual purpose of the static keyword? When should I declare static variable and methods?

答:
The static keyword can be a little hard for newbies to grasp. Its primary purpose is to identify a class member as not belonging to any single instance of the class, but instead to the class itself.

Without going into too much detail, C# (and Java) rigidly enforce the object-oriented ideal that all code and data must belong to an object, and therefore is limited in scope, visibility and lifetime. That's generally best practice wherever the fundamental tenet of an object representing some real-world thing applies. However, it doesn't always; sometimes what you need is a function or variable that you can get to from anywhere in code, without requiring you to pass around a reference to an object containing it, and with the guarantee that the data you are looking at or changing is exactly what everyone else is dealing with, and not a copy of it belonging to a different instance of an object.

Such behavior was available in C and C++ in the form of the "global" function or variable, which was not encapsulated in an object. So, as a compromise, C# and Java support "static scope", a halfway point between truly global code with no parent object and limited-scope instance members.

Any "code member" (function, property, field) declared as static comes into scope as of the first line of the program's main() function, and does not leave it until the main() function terminates. In plain English, a static member exists and can be used as long as the program is running. In addition, static members are invoked by calling them as members of the type itself, not members of any one instance of that type:

```<code>public class Foo
{
   public int MyInt {get;set;} //this is an "instance member"
   public static int MyStaticInt {get;set;} //this is a "static member"
}

...

var myFoo = new Foo();
myFoo.MyInt = 5; //valid
myFoo.MyStaticInt = 5; //invalid; MyStaticInt doesn't belong to any one Foo

Foo.MyInt = 5; //invalid; MyInt only has meaning in the context of an instance
Foo.MyStaticInt = 2; //valid
</code>```

This makes static members visible to any code that has knowledge of the type, whether or not they know about any single instance of it.

To answer your question, the primary benefit of marking something as static is that it becomes visible wherever the type itself is known, regardless of whether the consuming code has or can get an instance of the containing object. There's also a slight performance benefit; because the method is in static scope, it can only access other static members (of the same class or others), and whatever is passed in as a parameter. Therefore, the runtime does not have to resolve any reference to the current instance of the containing object, as it normally would have to for an instance method in order to provide context-specific state information.

Entire classes can also be marked static; by doing so, you tell the compiler that the class declaration will consist solely of static members, and thus cannot be instantiated. This is an easy way to ensure there is one, and only one, copy of an object in memory; make the class and everything in it static. However, it's very rare that this is the best solution to such a need. In a situation where exactly one copy of a set of data is required, the "singleton" is typically advocated instead; this is a non-static class, which uses a static accessor and a non-public constructor to provide access to a single instance of itself. Theoretically, a singleton provides much the same benefits of a fully static class, but with the added ability to use the class in an instance-based, object-oriented way.

Title: Understanding the static keyword

Body:
The static keyword can be a little hard for newbies to grasp. Its primary purpose is to identify a class member as not belonging to any single instance of the class, but instead to the class itself.

Without going into too much detail, C# (and Java) rigidly enforce the object-oriented ideal that all code and data must belong to an object, and therefore is limited in scope, visibility and lifetime. That's generally best practice wherever the fundamental tenet of an object representing some real-world thing applies. However, it doesn't always; sometimes what you need is a function or variable that you can get to from anywhere in code, without requiring you to pass around a reference to an object containing it, and with the guarantee that the data you are looking at or changing is exactly what everyone else is dealing with, and not a copy of it belonging to a different instance of an object.

Such behavior was available in C and C++ in the form of the "global" function or variable, which was not encapsulated in an object. So, as a compromise, C# and Java support "static scope", a halfway point between truly global code with no parent object and limited-scope instance members.

Any "code member" (function, property, field) declared as static comes into scope as of the first line of the program's main() function, and does not leave it until the main() function terminates. In plain English, a static member exists and can be used as long as the program is running. In addition, static members are invoked by calling them as members of the type itself, not members of any one instance of that type:

public class Foo
{
   public int MyInt {get;set;} //this is an "instance member"
   public static int MyStaticInt {get;set;} //this is a "static member"
}

...

var myFoo = new Foo();
myFoo.MyInt = 5; //valid
myFoo.MyStaticInt = 5; //invalid; MyStaticInt doesn't belong to any one Foo

Foo.MyInt = 5; //invalid; MyInt only has meaning in the context of an instance
Foo.MyStaticInt = 2; //valid

This makes static members visible to any code that has knowledge of the type, whether or not they know about any single instance of it.

To answer your question, the primary benefit of marking something as static is that it becomes visible wherever the type itself is known, regardless of whether the consuming code has or can get an instance of the containing object. There's also a slight performance benefit; because the method is in static scope, it can only access other static members (of the same class or others), and whatever is passed in as a parameter. Therefore, the runtime does not have to resolve any reference to the current instance of the containing object, as it normally would have to for an instance method in order to provide context-specific state information.

Entire classes can also be marked static; by doing so, you tell the compiler that the class declaration will consist solely of static members, and thus cannot be instantiated. This is an easy way to ensure there is one, and only one, copy of an object in memory; make the class and everything in it static. However, it's very rare that this is the best solution to such a need. In a situation where exactly one copy of a set of data is required, the "singleton" is typically advocated instead; this is a non-static class, which uses a static accessor and a non-public constructor to provide access to a single instance of itself. Theoretically, a singleton provides much the same benefits of a fully static class, but with the added ability to use the class in an instance-based, object-oriented way.


问:
How "viral" is the Affero GPL?
MongoDB is licensed under the AGPL, and interestingly, its licensing page says the following:

To make the above practical, we promise that your client application which uses the database is a separate work. To facilitate this, the mongodb.org supported drivers (the part you link with your application) are released under Apache license, which is copyleft free.

(Emphasis in the original.)

Is this possible? Could not a receiver of the services provided by a website that uses MongoDB argue that he uses a derived work of MongoDB and that he is entitled to its source code?

If it is in fact possible, I have two questions about it:

What is the point, then, of licensing MongoDB under the AGPL rather than the GPL? It seems to make the difference between the two moot.

Could I not then also write a simple AGPL'd "wrapper" around a similar library such as Berkeley DB and offer a similar Apache-licensed "driver" library to permit its use in websites that do not, then, need to have their source code published?

Also, how viral is the AGPL in general? If I take a GPL'd web application or other network server, and modify it to store its data in a Berkeley DB, would I be required to release the resulting source code (assuming, of course, that I allow public use of the service)? Likewise, how about a service that makes internal use of eg. OpenLDAP which uses Berkeley DB for storage but isn't itself AGPL'd? Where does one draw the line?

答:
No, a receiver of services provided using MongoDB has no standing to enforce its license.  Only a copyright holder can do that, and they've promised not to (which, at least in English law, means that they cannot), so there is nobody who is in a position to legally require you to comply with the actual text of the license.  Effectively, the MongoDB team have created a situation similar to the glibc linking exception to the GPL -- they've given you an extra right that you otherwise wouldn't have, by promising that they won't consider a certain class of use of their software as derivative, even in cases where it clearly actually is.

You can't, however, use a scheme like this to get around the requirements of somebody else's AGPL license, because only the copyright holder can make such a promise.

As to the point of this licensing scheme, I'm not privy to the MongoDB authors' reasoning, but the only thing I can think of is that it prevents somebody modifying the server and then setting up a cloud database service using it without releasing their modifications.  Perhaps this was something that concerned the original authors.

ContentLicense: CC BY-SA 3.0

Title: How "viral" is the Affero GPL?


问:
Force Derived Class to Implement Static Method C#
So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.

Also, the signature of these CRUD methods are similar.

E.g.
ClassA will have CRUD methods with these type of Signatures

public static List<ClassA> Get()

public static ClassA Get(int ID)

public static bool Insert(ClassA objA)

public static bool Update(int ID)

public static bool Delete(int ID)

ClassB will have CRUD signatures like

public static List<ClassB> Get()

public static ClassB Get(int ID)

public static bool Insert(ClassB objB)

public static bool Update(int ID)

public static bool Delete(int ID)

So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.

For E.g. BaseClass will have CRUD methods like

public virtual static List<BaseClass> Get()

public virtual static BaseClassGet(int ID)

public virtual static bool Insert(BaseClass objBase)

public virtual static bool Update(int ID)

public virtual static bool Delete(int ID)

But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.

So is there any way out?

Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.

Anything that can be done with Abstract class?

答:
Such methods shouldn't be static (what if you have to deal with two databases?) and they also shouldn't be on your entity classes.

Instead, you should have a separate type, that represents the storage for this entity. That type could be generic, so that code that's not entity-specific doesn't have to be repeated.

This way, inheritance works (storage for ClassA can inherit from some base storage) and you don't have to perform the nonsensical "I have to create a person to get a list of all persons".

This pattern is for example used by Entity Framework, there the storage type is called DbSet<T>.


问:
Managing Database version controlled migrations using a list/table
I'm not much of an expert in the area but I am aware that solutions already exist to managing database migrations in version control, e.g. sqitch and liquibase. However I'm currently planning a small hobby project and even sqitch looks like an annoying amount of cognitive overhead.

Idea

A migration is a (name, up action, down action). I was thinking of keeping a single column table (the migrations table) in the SQL database containing unique names of all of the migrations that had been run. Then in version controlled source code there would be a list (the migrations list) with the order of the migrations to run.

Pros:

(key) conflicts in the migrations list would be caught by the version control software, e.g. git, and then manually resolved;

a database can easily bring itself up to date by running the migrations in the migrations list that aren't in the migrations table in the order that they appear in the list;

a development database can rollback to previous schemas by running the down action for all of the migrations in the migrations table that occur before the target migration in the migrations list (might need to add a timestamp so that they can be removed in the right order);

it's simple enough that I'd be okay with writing an ad-hoc implementation for a project.

Cons:

the obvious xkcd critique;

maybe someone has done this before and it didn't work;

maybe no one has done this before because it wont work.

Question

So my question is, given that I want to handle schema migrations in version control but I don't want to make things complicated, is the above solution a good idea? I'm open to other solutions provided they automatically detect or resolve migration conflicts and are simple.

答:
The way you are planning to do migrations is essentially the same way that Entity Framework does it for .NET applications. It has a DatabaseMigrations table with a key that is the date/time with a unique string appended to it.

The code in a particular release is designed to work with a particular version of the database. It looks for the most recent migration in the migrations table, and applies up migrations until it has the database schema it needs. It can also do downward migrations, but these aren't automatic.

Here's where it differs from your solution: instead of the migration scripts being encoded as SQL as being run as scripts by the version control (if I understand what I read correctly), Entity Framework encodes the migrations as C# classes within the program, so upon database initialisation it will search for subclasses of "Migration" and instantiate them as appropriate. You can get an idea of what this looks like here.

I think the solution you've come up with is a good one. If you're comfortable implementing it, go for it.


答:
Jules' answer is exactly right. Allow me to intensify the final "why do it this way?" point.

AGPL says others cannot improve MongoDB privately, then offer services based on their "enhanced versions," without at least making those improvements available to MongoDB, Inc. (among others).

The AGPL is a response to criticism in the open source community that many cloud operators, Internet service providers, and some HPC and financal industry shops devote enormous resources to tuning, tweaking, and improving their open source deployments, yet because they never "distribute" products based on the code, are effectively immune to copyleft.

Distribution is the triggering event for when you have to share your improvements under GPL, yet many large, technically- and economically-important organizations are exempt from that. "Not fair!" thought the open source community. "You're taking advantage of our work, yet making limited or marginal contributions back to the community!"

The Free Software Foundation did not wish to radically change GPL when it moved from v2 to v3, and it already needed to make many changes regarding thorny IP issues--especially patents. But it still wanted to address the "service provider loophole." Thus the AGPL alternative. It's an option for those that fear that large service providers and customers will make improvements and not "give them back to the community" (or, for the more business-minded: "not give them back to those doing the primary development and investment").

AGPL results are mixed. There are not a lot of AGPL-licensed projects, at least in comparison to the gazillions of projects licensed under one of the other GPL variants, Apache, Mozilla, etc. Some large cloud shops respond, in effect: "Fine. We just won't use AGPL projects."

MongoDB is arguably the most important project under AGPL. As a cloud-generation document-oriented DBMS, it arguably has one of the strongest business cases for AGPL protections. UPDATE: In 2018, MongoDB moved away from AGPL to its own, very similar but not OSI-approved, Server Side Public License. Presumably because MongoDB, Inc. believed that in practice, AGPL was insufficient to protect its interests.

Title: How "viral" is the Affero GPL?

Body:
MongoDB is licensed under the AGPL, and interestingly, its licensing page says the following:

To make the above practical, we promise that your client application which uses the database is a separate work. To facilitate this, the mongodb.org supported drivers (the part you link with your application) are released under Apache license, which is copyleft free.

(Emphasis in the original.)

Is this possible? Could not a receiver of the services provided by a website that uses MongoDB argue that he uses a derived work of MongoDB and that he is entitled to its source code?

If it is in fact possible, I have two questions about it:

What is the point, then, of licensing MongoDB under the AGPL rather than the GPL? It seems to make the difference between the two moot.

Could I not then also write a simple AGPL'd "wrapper" around a similar library such as Berkeley DB and offer a similar Apache-licensed "driver" library to permit its use in websites that do not, then, need to have their source code published?

Also, how viral is the AGPL in general? If I take a GPL'd web application or other network server, and modify it to store its data in a Berkeley DB, would I be required to release the resulting source code (assuming, of course, that I allow public use of the service)? Likewise, how about a service that makes internal use of eg. OpenLDAP which uses Berkeley DB for storage but isn't itself AGPL'd? Where does one draw the line?

ContentLicense: CC BY-SA 4.0


问:
What should I do to scale out a high-traffic website?
What best practices should be undertaken for a website that needs to "scale out" to handle capacity?  This is especially relevant now that people are considering the cloud, but may be missing out on the fundamentals.

I'm interested in hearing about anything you consider a best practice from development-level tasks, to infrastructure, to management.

答:
I think that the key is going to be simple:

Have simple code. That means something that you look at and understand. As you expand and change servers you need to know what is going on. You also might need to add coders who need to quickly understand. Hooks and XML files that call random code that is not obvious is very bad.

Then you can test and find the problems.

Look here: http://blog.servint.net/2013/08/27/going-big-how-to-scale-a-website-part-1-infrastructure-that-scales/

We at stellarbuild try to make sure our websites scale without down time. That means you need to be able to know what your code does and where it does it. Even if you are testing a different machine you can't take too long to scale. Most people only start when it is almost too late, sadly. You can optimize only once you do that in my opinion.


问:
What is the simplest human readable configuration file format?
Current configuration file is as follows:

```<code>mainwindow.title = 'test'
mainwindow.position.x = 100
mainwindow.position.y = 200

mainwindow.button.label = 'apply'
mainwindow.button.size.x = 100
mainwindow.button.size.y = 30

logger.datarate = 100
logger.enable = True
logger.filename = './test.log'
</code>```

This is read with python to a nested dictionary:

```<code>{
  'mainwindow':{
    'button':{
      'label': {'value':'apply'},
       ...
  },
  'logger':{
     datarate: {'value': 100},
     enable: {'value': True},
     filename: {'value': './test.log'}
  },
  ...
}
</code>```

Is there a better way of doing this? The idea is to get XML type of behavior and avoid XML as long as possible. The end user is assumed almost totally computer illiterate and basically uses notepad and copy-paste. Thus the python standard "header + variables" type is considered too difficult.

The dummy user edits the config file, able programmers handle the dictionaries. Nested dictionary is chosen for easy splitting (logger does not need or even cannot have/edit mainwindow parameters).

答:
I say what you have (properties file) is already the best human readable configuration format. :)

Here are my arguments:

Properties file is just key/value pair. Easily readable by human.

Terse syntax, not like xml.

Easily nest-able, with '.', like in your example.

Flat structure allows easy diffing in a source controlled environment.

That last point is actually pretty important. Given that projects nowadays are all divided up into branches, configuration file can cause tons of pain when you are merging branches. Flat file format like properties file are easier to merge than tree structure file.

OwnerDisplayName: Juha


问:
How to send data between HTTP requests without user modifying it?
I'm currently developing a web application (using laravel) where I have a form that edit a resource. Something like this:

```<code><!-- URL: /editResource/3 -->
<form action="/editResource/3" method="POST">
     <!-- Input fields -->
</form>
</code>```

When I send the form the web application will update the resource 3.

But how I can prevent something like using developer tools to modify /editResource/3 to /editResource/4 and edit the wrong resource?

I'm not asking how to prevent some user editing other user resources; this can be accomplished by a simple validation, but I'm asking how to prevent user modifying this kind of data, since HTTP is stateless.

Thank you

EDIT: The question was misleading, I want to clarify that what I'm trying to find is a way to keep some information between requests, without user modifying it. I'm sending the information: 3 to the client so in the next request, the server knows that the user is editing the resource 3, but I want to do this without the risk generated by user changing this data.

答:
You can't.  If the data is on the user's end, the user is in control of it, not you.  Trying to change this is an arms race you don't want to get into.

Instead, worry about what you have control of: the server.  Validate data instead of blindly trusting it.  HTTP may be stateless, but your app on the server-side doesn't have to be!


答:
With static methods, you aren't going to get polymorphism or any sort of base class dispatch for these methods. So, I think you're looking for the 'wrong thing'. But don't let that get you down!

If you simply want to enforce that these methods are created on all classes deriving from a base, or interface, I can think of two easy ways off the top of my head.

First, in your unit test project, create a test that uses reflection across your assembly and fails if it finds any classes derived from your base that don't supply static implementations of your crud routines.

Second, create a T4 template that builds a junk class for each class derived from your base. In the junk class, place dummy calls to each crud method. When you compile, the compiler will choke on those missing static methods.

A non-technical solution would be to hit any developers who check in classes with missing static methods with a giant foam hammer during code-review.

Title: Force Derived Class to Implement Static Method C#

Body:
So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.

Also, the signature of these CRUD methods are similar.

E.g.
ClassA will have CRUD methods with these type of Signatures

public static List<ClassA> Get()

public static ClassA Get(int ID)

public static bool Insert(ClassA objA)

public static bool Update(int ID)

public static bool Delete(int ID)

ClassB will have CRUD signatures like

public static List<ClassB> Get()

public static ClassB Get(int ID)

public static bool Insert(ClassB objB)

public static bool Update(int ID)

public static bool Delete(int ID)

So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.

For E.g. BaseClass will have CRUD methods like

public virtual static List<BaseClass> Get()

public virtual static BaseClassGet(int ID)

public virtual static bool Insert(BaseClass objBase)

public virtual static bool Update(int ID)

public virtual static bool Delete(int ID)

But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.

So is there any way out?

Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.

Anything that can be done with Abstract class?


问:
Every function is a closure?
Wikipedia says, that closure - is a function, which has an access to variables, declared outside of the function. There is even an example:

```<code>function startAt(x)
   function incrementBy(y)
       return x + y
   return incrementBy

variable closure1 = startAt(1)
variable closure2 = startAt(5)
</code>```

But according to most programming languages (including python, javascript, swift, etc.) the next example is correct (written in python):

```<code># Script starts
test = "check"

def func(test2):

    def func2():
        return test2 == test

    return func2()

print func("check") // returns TRUE
# Script ends
</code>```

Basically, func is not a closure, but it obviously uses variable test, declared outside of the function. Does that mean func IS a closure?

Even in C++ you can run this:

```<code>std::string test = "check";

bool func(std::string test2) {
    if (test2 == test)
        return true;
    else
        return false;
}

int main() {
    if (func("check"))
        std::cout << "TRUE" << std::endl; // prints TRUE
}
</code>```

Eventually, this makes every function being a closure. Where am I wrong?

答:
Closures are an efficient way to implement functions.

I claim that every function is conceptually a closure, even in the few languages which don't have them.

The closed variables are then constants or static data inside the code. But in full-fledged closures (like in Ocaml, Scheme, Common Lisp, or C++11) the closed variables and the code are in the closure itself.

For instance, in C (and in C++98) functions are closures, but their closed (or free) variables are restricted to be static or global variables.

Closures also brings the possibility for anonymous functions, e.g. lambdas, which create closures with new closed variables (and that is something not possible in standard C). This is the abstraction operation of the λ-calculus (which does not exist in C, this is why every callback function -e.g. in GTK- takes some "client data" as an extra parameter).

From an implementation point of view, a function is always some code with some data required by the code. The data are the closed variables. For compiled C code, the data is wired in the code as fixed global or static variables (and changing these variables require recompilation), or as literal constants. So the only way of making an abstraction would be to regenerate some new code with some new variables in it.

Abstraction does not exist in standard C because there is no way to generate portably new functions. But you could use weird implementation-specific tricks. Imagine that you want to implement the translation generator function. In ocaml, the function to generate the translated-by delta function is

```<code> let transl delta = fun x -> x + delta
</code>```

and that is generating a new closure for every invocation. So in

```<code> let t3 = transl 3 in t3 5
</code>```

a new closure t3 is generated (but perhaps the optimizer is removing it) and the result is 8 (which is 3+5).

You could do insane tricks in C: on Linux, you would for example generate at runtime a new textual file t3mod.c containing

```<code> int t3(int y) { return y+3; };
</code>```

and you would compile that t3mod.c file in a shared object t3mod.so and dlopen it then dlsym it using "t3". This contrived way (using C code generation at runtime, then dynamically loading it) is a way of implementing abstractions in C and it is a way to generate dynamically new function pointers. Likewise, you might use JIT compiling libraries like e.g. libjit, LLVM (or libgccjit in future GCC 5). Read also about partial evaluation & eval & multi-stage programming (e.g. Meta OCaml...). See also J.Pitrat's blog entries on meta-combinatorial search & meta-bugs.

Title: Every function is a closure?

Body:
Closures are an efficient way to implement functions.

I claim that every function is conceptually a closure, even in the few languages which don't have them.

The closed variables are then constants or static data inside the code. But in full-fledged closures (like in Ocaml, Scheme, Common Lisp, or C++11) the closed variables and the code are in the closure itself.

For instance, in C (and in C++98) functions are closures, but their closed (or free) variables are restricted to be static or global variables.

Closures also brings the possibility for anonymous functions, e.g. lambdas, which create closures with new closed variables (and that is something not possible in standard C). This is the abstraction operation of the λ-calculus (which does not exist in C, this is why every callback function -e.g. in GTK- takes some "client data" as an extra parameter).

From an implementation point of view, a function is always some code with some data required by the code. The data are the closed variables. For compiled C code, the data is wired in the code as fixed global or static variables (and changing these variables require recompilation), or as literal constants. So the only way of making an abstraction would be to regenerate some new code with some new variables in it.

Abstraction does not exist in standard C because there is no way to generate portably new functions. But you could use weird implementation-specific tricks. Imagine that you want to implement the translation generator function. In ocaml, the function to generate the translated-by delta function is

 let transl delta = fun x -> x + delta

and that is generating a new closure for every invocation. So in

 let t3 = transl 3 in t3 5

a new closure t3 is generated (but perhaps the optimizer is removing it) and the result is 8 (which is 3+5).

You could do insane tricks in C: on Linux, you would for example generate at runtime a new textual file t3mod.c containing

 int t3(int y) { return y+3; };

and you would compile that t3mod.c file in a shared object t3mod.so and dlopen it then dlsym it using "t3". This contrived way (using C code generation at runtime, then dynamically loading it) is a way of implementing abstractions in C and it is a way to generate dynamically new function pointers. Likewise, you might use JIT compiling libraries like e.g. libjit, LLVM (or libgccjit in future GCC 5). Read also about partial evaluation & eval & multi-stage programming (e.g. Meta OCaml...). See also J.Pitrat's blog entries on meta-combinatorial search & meta-bugs.


答:
Imagine a Chinese person who doesn't know English who's trying to read your configuration file. Alternatively, imagine the configuration file is in Arabic (and that you don't known Arabic). Now ask yourself, is this really human readable?

Even if the reader does know English, they've still got no idea if "logger.datarate = 100" means 100 characters per second, or 100 GiB per hour, or 100 chickens per metric ton.

The most human readable file format, is a binary file with a decent GUI based dialog box/wizard/configurator (with internationalisation, help system, etc).

Title: What is the simplest human readable configuration file format?

Body:
Current configuration file is as follows:

```<code>mainwindow.title = 'test'
mainwindow.position.x = 100
mainwindow.position.y = 200

mainwindow.button.label = 'apply'
mainwindow.button.size.x = 100
mainwindow.button.size.y = 30

logger.datarate = 100
logger.enable = True
logger.filename = './test.log'
</code>```

This is read with python to a nested dictionary:

```<code>{
  'mainwindow':{
    'button':{
      'label': {'value':'apply'},
       ...
  },
  'logger':{
     datarate: {'value': 100},
     enable: {'value': True},
     filename: {'value': './test.log'}
  },
  ...
}
</code>```

Is there a better way of doing this? The idea is to get XML type of behavior and avoid XML as long as possible. The end user is assumed almost totally computer illiterate and basically uses notepad and copy-paste. Thus the python standard "header + variables" type is considered too difficult.

The dummy user edits the config file, able programmers handle the dictionaries. Nested dictionary is chosen for easy splitting (logger does not need or even cannot have/edit mainwindow parameters).


问:
Service Oriented Architecture - Component Responsibility
Working on an ecommerce project whereby a PHP application (back-end & non-customer facing) is currently responsible for processing an order from checkout stage through to generating profit/loss reports, processing the order and also performing various algorithms on behalf of a data science team.

The algorithmic components will be extracted out to a separate application (python).
PHP will be sending a json payload via curl through to a python application end-point / passing the payload over to a beanstalk queue or similar. However there is mixed opinion relating to which application is responsible for what.

The python developer wishes for the PHP dev to prepare and send over a large payload (qty, order value, user demographics etc.). Basically everything that the python developer requires in order to perform their algorithms.

The Php developer believes that all the python service requires is the order_id and from this, it can mine all the information it needs to run whatever algorithms it requires from the database. The php developer further argues, that if it is doing all the preparation of the data, then it may as well run the algorithms too as the passing responsibility to the service becomes redundant as much of the work has already been done.

Is there a right or wrong choice? could somebody provide any decent arguments for both sides to consider? Could anybody recommend any resources to assist in understanding of "internal" service oriented architecture?

答:
If the front end is made responsible for the 'large payload' for the processing by the Python back-end then you have a high degree of implementation coupling between the two systems that means maintenance, change management, or refactoring becomes more complex as both sides of the communication require significant interdependent re-engineeering in order to deal with the sending and receiving of the data.

In addition, implicitly, a new data store is being created in the transmission protocols (albeit transitory) as the data is formatted by the front end, transmitted, and parsed by the back-end.

By sending only the index into the data in the database you remove the issue of strong coupling and changes to either end of the process may take place with (usually) little dependence on the other side. You also have fewer places for errors to creep in because there is no formatting of large messages and then the parsing of those messages. In addition you have easy scalability because in future you would be able to add more front-end processing and more back-end processing without being concerned about which front-ends connect to which back-ends (that's all handled by the back-ends reading from a common data store).

This assumes you have, and will continue to have, direct access to the database by both systems i.e. that you're not planning to relocate either sides of the dialogue to remove systems in the future. If you relocate one of the systems away from direct connectivity to the database in future then

Of course the issues of sending large messages like this are manageable (for some systems there is no direct access to a shared database) but they add a layer of complexity that it appears you don't need to consider.


问:
Java 1.7 library with a Java 1.5 program - what are the options
I have a class library which is compiled with JDK 1.7 It uses several 1.7 features and classes and would be very difficult to get it recompiled in JDK 1.5.

This needs to integrate with an old legacy application with is currently running on JRE 1.5. The integration itself will be quick because the library has just 1 class and very little methods which need to be called from the application. The application owners aren't ready to move to Jre 1.7 immediately.

What are my options here? Is there a way to quickly convert the library into a Server on which the methods can be called remotely by the application? Are there any frameworks available to get this up and running quickly? I don't want to spend too much time on this because the application will move to 1.7 in a years time and this is a stop gap thing for the meantime.

Is there a better way to do this?

答:
In my experience there are relatively few difficulties involved in taking a java 1.5 application and running it on a later vm. Java is generally quite good at maintaining backward compatibility, and the few parts that are not compatible between versions are mostly well separated into the sun.* package hierarchy.

I would therefore aim to migrate the legacy application to a modern vm as soon as possible. There is little to be gained by delaying when it is likely to be a simpler job than the one you are proposing now.


问:
Finding the fewest sets which contain all items
I am wondering if there is a known algorithm for solving the following.

Data: There is a number of sets containing items. An item can be a member of more than one set.

Aim: return the minimum number of sets which between them contain all of the items, and avoid returning duplicate items as much as possible. For example:

Set 1: a

Set 2: a, b

Set 3: b, c

For this I would want to return sets 1 and 3. This is the fewest sets which combined contain at least 1 copy of all the items and duplicate items are kept to a minimum.

BTW - I will be looking to implement this in C#.

答:
Your problem is, I believe, NP-complete, so unless the number of sets you are dealing with is small, there isn't a guaranteed accurate solution that will run in a realistic time. You may plausibly be able to get accurate results by a global search (basically listing all possible combinations of sets and checking which one gives the best results) for up to about 20 sets, but not much larger problems than that.

Your requirement to minimize duplication makes it slightly different to the set cover problem as linked in the comments, and it may be that the approximate solution described in that article (essentially iterating the process of picking the choice that brings you closest to a solution until you have complete cover) doesn't work well enough for you as it entirely ignores your extra requirement.

If this is the case, I'd take an approach of using this algorithm to generate a first candidate solution, and then using simulated annealing in a similar manner to how it is applied to the traveling salesman problem as a final optimization step. I think this should result in something close to an optimal solution most of the time.


答:
I would try to avoid any solution which requires sharing a database between the front end and a back-end service, because my experience is that shared databases cause a lot more coupling that is much harder to detangle than a complex exchange format does.

I presume the data is initially gathered by the front end and then passed to the service once the order is complete. In this case, tying the back-end service in via the database means that any change in data format is likely to require both front and back end to change.

There are also security implications. It is desirable to run services in as secure an environment as possible; this often means they are run on a separate machine to the front end, which must be exposed to the internet at large. Ideally, we would have a secure database for the service which is not accessible from the front end machine; this minimizes the consequences of a compromise at the front end (preventing a hacker from, say, modifying already accepted orders to add additional items).  This is harder to achieve if the service must also access the front end databse. This may not be something you intend to do now, but by   choosing  to switch to soa you gain this kind of flexibility for future Iimprovements, so it would seem a shame to close them off before you really begin.

Title: Service Oriented Architecture - Component Responsibility

Body:
Working on an ecommerce project whereby a PHP application (back-end & non-customer facing) is currently responsible for processing an order from checkout stage through to generating profit/loss reports, processing the order and also performing various algorithms on behalf of a data science team.

The algorithmic components will be extracted out to a separate application (python).
PHP will be sending a json payload via curl through to a python application end-point / passing the payload over to a beanstalk queue or similar. However there is mixed opinion relating to which application is responsible for what.

The python developer wishes for the PHP dev to prepare and send over a large payload (qty, order value, user demographics etc.). Basically everything that the python developer requires in order to perform their algorithms.

The Php developer believes that all the python service requires is the order_id and from this, it can mine all the information it needs to run whatever algorithms it requires from the database. The php developer further argues, that if it is doing all the preparation of the data, then it may as well run the algorithms too as the passing responsibility to the service becomes redundant as much of the work has already been done.

Is there a right or wrong choice? could somebody provide any decent arguments for both sides to consider? Could anybody recommend any resources to assist in understanding of "internal" service oriented architecture?


答: You're going about this the wrong way. Any time you want to have a set of related methods like this and it looks like they should be static, consider the possibility that all this means is that you're trying to put them in the wrong place. In this case, you seem to be working towards the table data gateway pattern. Just move those methods into a separate class as virtual methods, have a single shared instance of each such class, and an abstract generic superclass to ensure the implementations are consistent.</p>


问:
Detect or Prevent Screen Capture Applications
I am building an app that displays very sensitive information and as such, I want to be able to either

Disable the ability to capture the screen

Redact the portion of my app that is on the screen during capture

Detect that a screen capture was made via an event, hook, log etc

Are any of the above even possible in Windows? if so, how?

UPDATE I have tried checking the windows event log for screen captures. I have searched for all over the web and I could not find any windows hooks that could do that. Any ideas would be highly appreciated

Context: There are two entities. An regular user (User A) who wants to use my app and a third party (User B) who has access to the machine before User A uses it. The intention of User B is steal the sensitive information using screen capture software during User A's session. So using VMs or anything that requires the current user's explicit action is not included

答:
I read a blog post on this a while ago: http://www.patrick-wied.at/blog/image-protection-on-the-web

His approach is to use interlacing images instead of single, still-standing images. You'd split up the image into several fractions, for example in the form of stripes, and display them alternating very fast. That way, if you try to cap the screen, you will only get a - possibly unreadable, depending on your algorithm - fraction of the original picture.

On windows, I'd attempt to overlay my application with several pictures with transparent stripes. Perhaps you could only overlay the text boxes, or make them alternate between visible/invisible...

To circumvent this, you'd have to painstakingly take repeated screencaps and puzzle them together, or, as noted by Jörg W Mittag, use a DSLR with a slow shutter speed.

I'm not really sure if this is actually a practical solution for your problem, but I find the approach ingenious.


问:
Plugin/modular architecture - deployment concerns
I'm developing a desktop application in .Net that follows a plugin architecture, something like this:-

I have a "core" .Net solution, containing the desktop exe project, and a handful of class library projects. These classes provide all sorts of shared/common functionality, and are referenced by the application exe and individual modules.

Each module lives in its own .Net solution. The solution has its own copy of the above shared library DLLs that the module's project(s) reference.

End-user installation really just involves deploying the core exe & DLLs, along with the modules' DLLs required at that site, into one folder. I've got no problem with the mechanism used by the core exe to "discover" which modules are present, then load & initialise them.

My concerns are around managing and deploying the DLLs. In an ideal world I should be able to make a change to "module X" and redeploy just that module's DLLs. However it's feasible that a change may also involve updating one of the shared libraries. When I redeploy these updated DLLs, the updated shared library functionality could break other modules (or even the application exe) that reference it. I guess what I should be doing in this scenario is to rebuild/redeploy all solutions, not just "module X".

An easier approach may be to treat the "core" and all modules as a single product, and redeploy everything in every release, even if it's just a change to one module. But it feels like I would be losing one of the advantages of a plugin architecture - I should be able to release a new version of a module in isolation.

Any thoughts? Or are such DLL referencing issues an unavoidable part of using a plugin architecture?

答:
I would take an approach that shared libraries are the responsibly of the core, and that modules can be updated however they want on an individual basis except when that requires an update to a shared library.

Additionally, I would track versions of the libraries by keeping a single version number for the core platform which is incremented at each release, and by having modules know which core version they require. This would make tracking down version mismatch issues simpler.

The advantage of this is that module development can carry on mostly independently of the core platform and each other, hopefully with only occasional updates required to the core.


问:
Python: Object initialised inside a Class?
Is possible and, if so, common practice to initialize an object inside a class in Python?</p>

```<code>self.field = Class()
</code>```

答: Everything in Python is an object, so yes, this is common practice. You could not create a meaningful Python program without creating other instances in your own classes.</p>


问:
Single line comments for multiple indented lines of code
After many years of coding, trying various programming styles, weeding out unreadable or impractical stuff, I still can't figure out one thing: what is the best way to single-line-comment multiple lines of indented code.

1.

```<code>    setup_checkpoint();
//    if (object->looks_suspicious())
//        guard->full_body_scan(object);
</code>```

2.

```<code>    setup_checkpoint();
    // if (object->looks_suspicious())
    //     guard->full_body_scan(object);
</code>```

3.

```<code>    setup_checkpoint();
    // if (object->looks_suspicious())
        // guard->full_body_scan(object);
</code>```

Please, don't suggest multiline commenting, because sometimes you want to leave that possibility for bigger blocks, which may include smaller pieces of comments.

答:
As I see it, the importance of source code formatting is secure and fast navigation. That's why line comments should safely been skipped, of course without reading them.

As to distinguish comments (//) and documentation (///) from so-called "commented-out blocks" in committed source code, I decided to use two special line comment styles. This was several years ago and I do not regret it.

1) //<< a block that is part of a "transactional" deletion:

```<code>//<< /// what something does...
//<< void something_obsolet()
//<< {
//<<     some_stuff();
//<< }
</code>```

2) //<? marks a deletion whose effect I'm currently checking in the IDE:

```<code>if (condition) {
    do_something();
//<? } else {
//<?             do_something_else();
}
</code>```

Of course, I use version control to managing variants. But (1) when deleting different corresponding parts, I change between compiling and searching to get rid of all of its remains. Whenever I find comments of this style in committed code, I delete it without even thinking about it. Even if in very rare cases, I use a special comment style (2) for testing particular deletions within an IDE, because I cannot predict the next phone ring, this style is my most short-lived one.

Thus the question about indentation becomes secondary, but as I observed putting the comment-out marks leftmost, right at the beginning of the line, seems to work best...

Body:
As I see it, the importance of source code formatting is secure and fast navigation. That's why line comments should safely been skipped, of course without reading them.

As to distinguish comments (//) and documentation (///) from so-called "commented-out blocks" in committed source code, I decided to use two special line comment styles. This was several years ago and I do not regret it.

1) //<< a block that is part of a "transactional" deletion:

//<< /// what something does...
//<< void something_obsolet()
//<< {
//<<     some_stuff();
//<< }

2) //<? marks a deletion whose effect I'm currently checking in the IDE:

if (condition) {
    do_something();
//<? } else {
//<?             do_something_else();
}

Of course, I use version control to managing variants. But (1) when deleting different corresponding parts, I change between compiling and searching to get rid of all of its remains. Whenever I find comments of this style in committed code, I delete it without even thinking about it. Even if in very rare cases, I use a special comment style (2) for testing particular deletions within an IDE, because I cannot predict the next phone ring, this style is my most short-lived one.

Thus the question about indentation becomes secondary, but as I observed putting the comment-out marks leftmost, right at the beginning of the line, seems to work best...


问:
Program to find Orthogonal Matrices
I have been trying to find orthogonal matrix of order n where first row will be given as 1/√n, 1/√n, .... n times.

The second row will be a vector such that dot product of it with the row above and below will be zero and so on. Means, in a matrix of order 3, the 3rd row will be the cross product of first 2 rows.

How do I approach such a problem?

答:
Extend the given row vector with n-1 vectors forming a set of n linear independent vectors. For example,

```<code>(1,0,0,...,0,0),
(0,1,0,...,0,0),
...
(0,0,0,...,1,0),
</code>```

should be sufficient. Afterwards, you apply the Gram-Schmidt process to these vectors. Since Gram-Schmidt keeps the first vector unchanged, the result will be n orthogonal row vectors, forming the orthogonal matrix you are looking for.

Title: Program to find Orthogonal Matrices

Body:
Extend the given row vector with n-1 vectors forming a set of n linear independent vectors. For example,

(1,0,0,...,0,0),
(0,1,0,...,0,0),
...
(0,0,0,...,1,0),

should be sufficient. Afterwards, you apply the Gram-Schmidt process to these vectors. Since Gram-Schmidt keeps the first vector unchanged, the result will be n orthogonal row vectors, forming the orthogonal matrix you are looking for.


答: I'd store the data server side in a session object or user profile record and then send the unmodified data each time.</p>

Title: How to send data between HTTP requests without user modifying it?

Body:
I'm currently developing a web application (using laravel) where I have a form that edit a resource. Something like this:

```<code><!-- URL: /editResource/3 -->
<form action="/editResource/3" method="POST">
     <!-- Input fields -->
</form>
</code>```

When I send the form the web application will update the resource 3.

But how I can prevent something like using developer tools to modify /editResource/3 to /editResource/4 and edit the wrong resource?

I'm not asking how to prevent some user editing other user resources; this can be accomplished by a simple validation, but I'm asking how to prevent user modifying this kind of data, since HTTP is stateless.

Thank you

EDIT: The question was misleading, I want to clarify that what I'm trying to find is a way to keep some information between requests, without user modifying it. I'm sending the information: 3 to the client so in the next request, the server knows that the user is editing the resource 3, but I want to do this without the risk generated by user changing this data.


问:
How do people deal with Android fragmentation?
I've spent the past few years working on iOS apps, and I'm now giving some serious consideration to creating an Android port of one of my apps.

I'm sure that complaints about fragmentation are a frustrating cliche to experienced Android programmers, but as an iOS programmer, I'm quite honestly overwhelmed by the number of configurations and devices that my app might end up running on.

There are literally thousands of Android devices in the wild, but I know there are successful Android developers in the world and I know they're not testing or developing for thousands of different devices.

So how can a relatively small company deal with fragmentation? Is it possible to pick the five or six most popular devices, focus on those and prevent the app from being installed on any other devices? Are there any other strategies for practically dealing with the number of different configurations an app will face?

答:
One resource to consider is vendor loaner or rental programs for development partners (developer partner programs). Some provide short-term access for testing purposes affordably, perhaps even free.

Most of the hardware vendors have developer programs, which offer hardware for reduced costs or even free (e.g. Samsung, Motorola, Apple, BlackBerry (for BlackBerry Alliance Members), LG). Check them out for the devices you want/need.

There are publicly accessible 'physical' test labs that you can just walk into (or reserve time). They are usually called open device labs: starting point, Google search. Check out if there are any in your neighbourhood and what devices they have.

There's the occasional 'crowdsourced' testing community like uTest that you can ask around.

Note that there are also many on-line services for testing your apps on many devices like AppThwack, TestFlight, TestObject, TestFairy, Keynote a.k.a. DeviceAnywhere, or Xamarin test cloud that maybe have the device you want to test on.

You would also use these before releasing your app, and although these are not 'definitive' testing platforms (there's much to be said for testing on real devices), any tests helps.

Note: Useful overview article


问:
What do I use for a variant in a UML class diagram?
Does standard UML specify how a variant (aka tagged union, discriminated union, sum type, etc) should be depicted in a class diagram? </p>

答:
Composition could likely be used to denote tagged unions in a UML class diagram. Composition is the "has a" relationship and a tagged union has a tag and a value. You can use multiplicity and role names or ownership indicators.

However, something to consider is that class diagrams are typically geared toward representing class relationships in an object-oriented language. Other diagram types may be less specific to object-orientation, such as deployment diagrams or component diagrams. You may want to consider other notations beyond just using UML and emphasize clearly communicating a design over sticking to one standard.


问:
Understand SGML and HTML
When I read the HTML 4 Specification.

The document says :

Each markup language defined in SGML is called an SGML application. An SGML application is generally characterized by:

An SGML declaration.

A document type definition (DTD).

A specification that describes the semantics to be ascribed to the markup. This specification also imposes syntax restrictions that cannot be expressed within the DTD.

Document instances containing data (content) and markup. Each instance contains a reference to the DTD to be used to interpret it.

From above paragraph, My understanding is the HTML is an SGML application , Is it right?
And I know there are three types(Traditional, Strict and Frameset) of DTD for the HTML4 (no DTD for HTML5). so for the below sample of Html. What is the DTD type? Thanks.

```<code><Html>
  <head>
  </head>
  <body>
    <p>the test html</p>
  </body>
</Html>
</code>```

答:
From HTML 2.0 to HTML 4.01, HTML was nominally defined as an SGML application, as described in the quotation from the HTML 4.01 spec. It was never implemented that way. At least there has never been any published software that actually implements HTML as an SGML application. This is reflected in clause B.3.3 SGML features with limited support of the spec; it described features “that aren't widely supported by HTML user agents”, which is a gross understatement; strike out that “widely”.

The sample does not contain any document type declaration (doctype declaration), so it does not specify any DTD. It is not a conforming HTML 4.01 document, since HTML 4.01 requires that one of three document type declarations be used (and it makes the title element mandatory). Strictly speaking, it is not HTML at all, though browsers will happily treat it as HTML. Formally, that piece of code is an SGML document, since SGML does not require the use of a document type declaration. But as such, it has no meaning; it is pure syntax.

Title: Understand SGML and HTML


问:
How would one allow a client to query a graph database in Smalltalk, without exposing all of Smalltalk?
Is there any example of Smalltalk being used as a query language?

What I am looking for is: a system or an application where the Smalltalk nature of the application is hidden or irrelevant to the end-user and portions of the language is exposed only for querying the object model underneath (be it application objects, document objects, a simulation or similar). For example a user interface where user defines queries in Smalltalk – either as the predicate portion of the query or the predicate + some other information entered through other user interface elements. The application then wraps it into blocks and applies appropriate filtering functions such as select: or detect: depending on the goal of the query.

Analogy would be SQL interface, however that would require relationship model to gain real benefits from it. I'm looking for a language use where the queried model is just a ad-hoc object graph.

@JavierBurroni suggest "GemStone/S 64 Bit Programming Guide chapter 6" (actually Chapter 7 in the 2012 edition) as an example. Which is nicely explained, but still typical smalltalk use within the Smalltalk environment by the Smalltalk developers.

Is there a such thing?

答:
.NET already does this; it's called Linq.  Linq is basically SQL for object collections.

In C#, it looks like this:

```<code>var q =
  customers.
  where(c => c.City == "Montreal").
  select(c => c.CompanyName);
</code>```

and in Smalltalk, it looks like this:

```<code>q :=
  customers
    where: [ :c | c city = 'Montreal' ]
    select: [ :c | c companyName ].
</code>```

or this:

```<code>((people
    select:  [ :person | person type = #adult ])
    reject:  [ :person | person location = 'New York' ])
</code>```

To hide the Smalltalk representation from your users, you would have to create some sort of domain-specific language that is parsed and processed by Smalltalk. SQL is one such language, but it could be simpler than that.  It could merely be a wrapper around the Smalltalk semantics.

For an example of how this might work, look at the Biosmalltalk project.

Of course, all this depends on having some sort of reasonable organizational structure to your data.  If your goal is to query data having an arbitrary representation, then you need to look into things like graph databases or dynamically-generated queries.

Further Reading

Is C# turning into Smalltalk?

Your language features are my libraries

Dynamic Linq

Body:
.NET already does this; it's called Linq.  Linq is basically SQL for object collections.

In C#, it looks like this:

var q =
  customers.
  where(c => c.City == "Montreal").
  select(c => c.CompanyName);

and in Smalltalk, it looks like this:

q :=
  customers
    where: [ :c | c city = 'Montreal' ]
    select: [ :c | c companyName ].

or this:

((people
    select:  [ :person | person type = #adult ])
    reject:  [ :person | person location = 'New York' ])

To hide the Smalltalk representation from your users, you would have to create some sort of domain-specific language that is parsed and processed by Smalltalk. SQL is one such language, but it could be simpler than that.  It could merely be a wrapper around the Smalltalk semantics.

For an example of how this might work, look at the Biosmalltalk project.

Of course, all this depends on having some sort of reasonable organizational structure to your data.  If your goal is to query data having an arbitrary representation, then you need to look into things like graph databases or dynamically-generated queries.

Further Reading

Is C# turning into Smalltalk?

Your language features are my libraries

Dynamic Linq


问:
user verification value - where to store
Quick question as relates to database.

Where would you store the value of "UserVerified"? (The one that occurs after the user has checked his email and clicked on the "Verify" link with the hash value at the end).

Would you store it in the User table? (Along with username, hash) ?

Or in the UserProfile table (along with first name, last name, email, phone, etc) ?

Please note that both tables will always contain 1 entry for a user, such that when a user is created, automatically a userprofile is created as well.

答: Based on your description of the two tables, it sounds like User contains metadata about the user, such as the hash field (and probably other things the user never enters, but are still important to keep track of in the system). So if you consider isVerified to also be metadata, then it should probably go in the User table with the related fields.


问:
Application use on website
Is there a good way to run a C# application on clientside in lieu of JavaScript? I have done some front end work with JavaScript and backend C# for web developing at an old job, but I am interested in hosting a website myself soon. I have a C# application I would like to be open source, but before people care to download I'd like them to be able to use it. At its basic level it's a simple text editor, but there's much more to it in the nitty gritty. I could write it in JavaScript, but it would require me to keep documentation and up to date changes on JavaScript and C# in that case.

I was thinking of creating an AJAX panel and somehow loading my winform application into a frame, but I don't know how or what words to google because I've never done it before except AJAX.

答:
An ASP.NET WebForms application will be your best bet in the short term.

Your skills at WinForms will be largely transferable, however you'll need to make yourself familiar with where you're WinForm is relying on persisted state objects. These pieces of data that need to be persisted throughout the lifetime of the application, that are not part of server-side controls themselves, will need to be manually persisted via either the ViewState or Session state.

WebForms is not an ideal technology for the stateless web, but it was designed for developers that are familiar with Winform development.

Diving into full-blown stateless MVC has a considerable learning curve if you aren't used to web development.

Title: Application use on website


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答:
C is a great language for System programming

I would use C if I implemented some harware drivers. And I would use C if I implement my own Operating System kernel or my own Virtual Machine.

It is a very good language to do low-level things if you have to deal with hardware or low-level OS APIs for Windows API, Linux, Mac OS X, Solaris and so on... Embedded systems has usually good support for C with a compiler + development kit.

ContentLicense: CC BY-SA 2.5


问:
How to represent an optional-to-optional relationship in a database
I have two types of users: a CRM user and a system user. We have a record of every CRM user, thanks to a nightly sync that we run (so we don't have to hit the CRM API every time). We have system users that don't have CRM accounts. We also have CRM users that aren't in our system. If a system user happens to have a CRM account, we want to link the two accounts together. So, this is an optional-to-optional relationship.

Originally, I put a foreign key on the CRM user table. This was enough for us to determine if a system user was in CRM or the other way around. I could have put the foreign key on the system user table just as easily. However, there's the off chance that, in the future, we will be linking other types of accounts to our system accounts, as well. I didn't want to keep adding new null-able columns to the system user table when I could just as easily add them to new tables.

I am using Entity Framework and it seems to hate optional-to-optional relationships. The only way I have been able to configure this relationship is using a one-to-many relationship. In the system user entity, I have a collection of CRM users. This works, except the code needs to constantly say user.CRMUsers.FirstOrDefault() which makes the code awkward and hard to read. Going in the opposite direction is fine, because the CRM user just links to a single system user (or null).

This has got me thinking that maybe I am representing optional-to-optional relationships incorrectly in my database. There's no clear reason why the foreign key should be on one table or the other. Perhaps a many-to-many table with a unique constraint is better (but I think that would mean having a collection in both entities, yuck!).

So, how should I be representing these types of relationships? Will EF understand that representation?

答:
You should represent them as many to many.  optional to optional does not really describe the relationship of the data

Many to many does not 'require' either side to actually exist unless you enforce it through triggers, not null foreign key fields and the like.

A many to many relationship can also be thought of, and referenced as, a mapping table.


问:
Convert procedural code to object oriented
I have a PHP application (a web service). It consists of files grouped in directories by theme like :

```
    /customer
        /search.php
```

with this example content :

```<code>Auth::authenticate($options);
$db = new Db($options);
$db->query("select ... ");
echo json_encode($db->fetch_all();
</code>```

A basic way to convert this code to object oriented code would be to map a URL /object/method.php to $Object->method($post_parameters) using a basic router. The above example code would become (in file /Customer.php):

```<code>class Customer
{
    function search($post_parameters)
    {
        Auth::authenticate($options);
        $db = new Db($options);
       $db->query("select ... ");
       echo json_encode($db->fetch_all();
   }
}
</code>```

Advantages

It is that it is easy to convert the code, it will not take much time.

I can use autoloading of the classes.

Disadvantages :

It is merely formally object oriented. It still remains mainly procedural code.

I still call Auth::authenticate() and create a new Db in each method (but not always with the same parameters).

Am I on the right track ? Is there a better way to approach that code refactoring ? Or is there an obvious next step ?

Do you think is what I described a legitiate use case for procedural code ? Is there a middle ground between this and an object oriented approach with a full fledged framework like Zend framework for instance ?

答:
There is nothing so bad that it cannot be used as a bad example, at least. To me, your example is not even "formally object oriented", it is just as procedural as the original. The only noteable thing you changed is the namespace where the search function "lives".

A customer object should represent the data and some business logic of a customer (there is not even one attribut in your class, and the search method does not work on a customer object). A "search" function for customers could return a customer object, or a collection of customer objects (echoing some json string has nothing to do with that). Such a function is probably not a member function of a customer class (it could be placed there as a static function, or somewhere else, for example, in a CustomerFactory). And a reasonable customer search should avoid coupling to global attributes and methods (like $options, Db, or  Auth::authenticate).

So if your goal is to introduce more "object oriented structure" into your program, you may be better off by doing a little bit more upfront design first. For example, start by designing a customer class first and think about how a search function must look like for delivering such objects.


答:
As long as you are the only vendor for all "plugins", and as long the invidual modules don't need hundreds of MB disk space, I suggest you put always all DLLs into every released package, and treat everything as one product, with one version number. This makes deployment easier, since you don't need separate packages for partial updates, and if you need a complete reinstall of the newest version, you can use exactly the same package.

However, if you are going to use your plugin architecture to let your modules get their own lifecycle, mostly independent from the core, plan for modules as if they were provided by a different vendor. Make sure there is a stable interface between the modules and the core, and make sure that the modules' libraries don't collide with the libraries of the core (for example, avoid installing them to the same folder). Even if you have a shared library which is used in the core and reused in one of your modules, make sure the core and the modules can use different versions of that shared library simultanously. And make sure your product and your modules have their own version numbers. Then you can deploy your core and your plugins separately.

The second option will typically involve more effort in configuration management than the first, so just "because you have a plugin architecture and can treat your modules as different products" does not mean you must do so, and that you lose something important when deploying everything in one package.

Title: Plugin/modular architecture - deployment concerns

Body:
I'm developing a desktop application in .Net that follows a plugin architecture, something like this:-

I have a "core" .Net solution, containing the desktop exe project, and a handful of class library projects. These classes provide all sorts of shared/common functionality, and are referenced by the application exe and individual modules.

Each module lives in its own .Net solution. The solution has its own copy of the above shared library DLLs that the module's project(s) reference.

End-user installation really just involves deploying the core exe & DLLs, along with the modules' DLLs required at that site, into one folder. I've got no problem with the mechanism used by the core exe to "discover" which modules are present, then load & initialise them.

My concerns are around managing and deploying the DLLs. In an ideal world I should be able to make a change to "module X" and redeploy just that module's DLLs. However it's feasible that a change may also involve updating one of the shared libraries. When I redeploy these updated DLLs, the updated shared library functionality could break other modules (or even the application exe) that reference it. I guess what I should be doing in this scenario is to rebuild/redeploy all solutions, not just "module X".

An easier approach may be to treat the "core" and all modules as a single product, and redeploy everything in every release, even if it's just a change to one module. But it feels like I would be losing one of the advantages of a plugin architecture - I should be able to release a new version of a module in isolation.

Any thoughts? Or are such DLL referencing issues an unavoidable part of using a plugin architecture?


问:
Why squash git commits for pull requests?
Why does every serious Github repo I do pull requests for want me to squash my commits into a single commit?

I thought the git log was there so you could inspect all your history and see exactly what changes happened where, but squashing it pulls it out of the history and lumps it all into one commit.  What is the point?

This also seems to go against the "commit early and commit often" mantra.

答:
Because often the person pulling a PR cares about the net effect of the commits "added feature X", not about the "base templates, bugfix function X, add function Y, fixed typos in comments, adjusted data scaling parameters, hashmap performs better than list"... level of detail

If you think that your 16 commits are best represented by 2 commits rather than 1 "Added feature X, re-factored Z to use X" then that is probably fine to propose a pr with 2 commits, but then it might be best to propose 2 separate pr's in that case (if the repo still insists on single commit pr's)

This doesn't go against the "commit early and commit often" mantra, as in your repo, while you are developing you still have the granular details, so you have minimal chance of losing work, and other people can review/pull/propose pr's against your work while the new pr is being developed.


问:
Java 1.7 library with a Java 1.5 program - what are the options
I have a class library which is compiled with JDK 1.7 It uses several 1.7 features and classes and would be very difficult to get it recompiled in JDK 1.5.

This needs to integrate with an old legacy application with is currently running on JRE 1.5. The integration itself will be quick because the library has just 1 class and very little methods which need to be called from the application. The application owners aren't ready to move to Jre 1.7 immediately.

What are my options here? Is there a way to quickly convert the library into a Server on which the methods can be called remotely by the application? Are there any frameworks available to get this up and running quickly? I don't want to spend too much time on this because the application will move to 1.7 in a years time and this is a stop gap thing for the meantime.

Is there a better way to do this?

答:
Why don't you write a bridge? Something that uses shared memory or something similar. Looking at your options, I am not sure, how fast this thing is supposed to work. But that's the only alternative I can think of.

Googling tells me this won't be easy either... Unless you use imq or something...

Methods to share memory or state across JVMs? still not easy


答:
So that you have a clear and concise git history that clearly and easily documents the changes done and the reasons why.

For example a typical 'unsquashed' git log for me might look like the following:

```<code>7hgf8978g9... Added new slideshow feature, JIRA # 848394839
85493g2458... Fixed slideshow display issue in ie
gh354354gh... wip, done for the week
789fdfffdf... minor alignment issue
787g8fgf78... hotfix for #5849564648
9080gf6567... implemented feature # 65896859
gh34839843... minor fix (typo) for 3rd test
</code>```

What a mess!

Whereas a more carefully managed and merged git log with a little additional focus on the messages for this might look like:

```<code>7hgf8978g9... 8483948393 Added new slideshow feature
787g8fgf78... 5849564648 Hotfix for android display issue
9080gf6567... 6589685988 Implemented pop-up to select language
</code>```

I think you can see the point of squashing commits generally and the same principle applies to pull requests - Readability of the History.  You may also be adding to a commit log that already has hundreds or even thousands of commits and this will help keep the growing history short and concise.

You want to commit early and often.  It's a best practice for many reasons.  I find that this leads me to frequently have commits that are "wip" (work-in-progress) or "part A done" or "typo, minor fix" where I am using git to help me work and give me working points that I can go back to if the following code isn't working out as I progress to get things working.  However I do not need or want that history as part of the final git history so I may squash my commits - but see notes below as to what this means on a development branch vs. master.

If there are major milestones that represent distinct working stages it's still ok to have more than one commit per feature/task/bug.  However this can often highlight the fact that the ticket under development is 'too big' and needs to be broken down into smaller pieces that can standalone, for example:

```<code>8754390gf87... Implement feature switches
</code>```

seems like "1 piece of work".  Either they exist or they don't!  Doesn't seem to make sense to break it out.  However experience has shown me that (depending on organizational size and complexity) a more granular path might be:

```<code>fgfd7897899... Add field to database, add indexes and a trigger for the dw group
9458947548g... Add 'backend' code in controller for when id is passed in url.
6256ac24426... Add 'backend' code to make field available for views.
402c476edf6... Add feature to UI
</code>```

Small pieces mean easier code reviews, easier unit testing, better opportunity to qa, better alignment to Single Responsibility Principle, etc.

For the practicalities of when to actually do such squashes, there are basically two distinct stages that have their own workflow

your development, e.g. pull requests

your work added to the mainline branch, e.g. master

During your development you commit 'early and often' and with quick 'disposable' messages.  You may wish to squash here sometimes, e.g. squashing in wip and todo message commits.  It is ok, within the branch, to retain multiple commits that represent distinct steps you made in development.  Most of the squashes you choose to do should be within these feature branches, while they are being developed and before merge to master.

When adding to the mainline branch you want to the commits to be concise and correctly formatted according to the existing mainline history.  This might include the Ticket Tracker system ID, e.g. JIRA as shown in examples.  Squashing doesn't really apply here unless you want to 'roll-up' several distinct commits on master.  Normally you don't.

Using --no-ff when merging to master will use one commit for the merge and also preserve history (in the branch).  Some organizations consider this to be a best practice.  See more at https://stackoverflow.com/q/9069061/631619 You will also see the practical effect in git log where a --no-ff commit will be the latest commit, at the top of the HEAD (when just done), whereas without --no-ff it may be further down in the history, depending on dates and other commits.

Title: Why squash git commits for pull requests?

Body:
Why does every serious Github repo I do pull requests for want me to squash my commits into a single commit?

I thought the git log was there so you could inspect all your history and see exactly what changes happened where, but squashing it pulls it out of the history and lumps it all into one commit.  What is the point?

This also seems to go against the "commit early and commit often" mantra.

Body:
So that you have a clear and concise git history that clearly and easily documents the changes done and the reasons why.

For example a typical 'unsquashed' git log for me might look like the following:

7hgf8978g9... Added new slideshow feature, JIRA # 848394839
85493g2458... Fixed slideshow display issue in ie
gh354354gh... wip, done for the week
789fdfffdf... minor alignment issue
787g8fgf78... hotfix for #5849564648
9080gf6567... implemented feature # 65896859
gh34839843... minor fix (typo) for 3rd test

What a mess!

Whereas a more carefully managed and merged git log with a little additional focus on the messages for this might look like:

7hgf8978g9... 8483948393 Added new slideshow feature
787g8fgf78... 5849564648 Hotfix for android display issue
9080gf6567... 6589685988 Implemented pop-up to select language

I think you can see the point of squashing commits generally and the same principle applies to pull requests - Readability of the History.  You may also be adding to a commit log that already has hundreds or even thousands of commits and this will help keep the growing history short and concise.

You want to commit early and often.  It's a best practice for many reasons.  I find that this leads me to frequently have commits that are "wip" (work-in-progress) or "part A done" or "typo, minor fix" where I am using git to help me work and give me working points that I can go back to if the following code isn't working out as I progress to get things working.  However I do not need or want that history as part of the final git history so I may squash my commits - but see notes below as to what this means on a development branch vs. master.

If there are major milestones that represent distinct working stages it's still ok to have more than one commit per feature/task/bug.  However this can often highlight the fact that the ticket under development is 'too big' and needs to be broken down into smaller pieces that can standalone, for example:

8754390gf87... Implement feature switches

seems like "1 piece of work".  Either they exist or they don't!  Doesn't seem to make sense to break it out.  However experience has shown me that (depending on organizational size and complexity) a more granular path might be:

fgfd7897899... Add field to database, add indexes and a trigger for the dw group
9458947548g... Add 'backend' code in controller for when id is passed in url.
6256ac24426... Add 'backend' code to make field available for views.
402c476edf6... Add feature to UI

Small pieces mean easier code reviews, easier unit testing, better opportunity to qa, better alignment to Single Responsibility Principle, etc.

For the practicalities of when to actually do such squashes, there are basically two distinct stages that have their own workflow

your development, e.g. pull requests

your work added to the mainline branch, e.g. master

During your development you commit 'early and often' and with quick 'disposable' messages.  You may wish to squash here sometimes, e.g. squashing in wip and todo message commits.  It is ok, within the branch, to retain multiple commits that represent distinct steps you made in development.  Most of the squashes you choose to do should be within these feature branches, while they are being developed and before merge to master.

When adding to the mainline branch you want to the commits to be concise and correctly formatted according to the existing mainline history.  This might include the Ticket Tracker system ID, e.g. JIRA as shown in examples.  Squashing doesn't really apply here unless you want to 'roll-up' several distinct commits on master.  Normally you don't.

Using --no-ff when merging to master will use one commit for the merge and also preserve history (in the branch).  Some organizations consider this to be a best practice.  See more at https://stackoverflow.com/q/9069061/631619 You will also see the practical effect in git log where a --no-ff commit will be the latest commit, at the top of the HEAD (when just done), whereas without --no-ff it may be further down in the history, depending on dates and other commits.


问:
Is software inherently buggy and hence, vulnerable?
Could no amount of formal analysis, type/rule checking prevent it's exploitation?
How about a fully verified kernel such as SEL4 ?</p>

答:
According to mathematician Kurt Gödel's incompleteness theorems:

The first incompleteness theorem states that no consistent system of axioms whose theorems can be listed by an "effective procedure" (e.g., a computer program, but it could be any sort of algorithm) is capable of proving all truths about the relations of the natural numbers (arithmetic). For any such system, there will always be statements about the natural numbers that are true, but that are unprovable within the system. The second incompleteness theorem, an extension of the first, shows that such a system cannot demonstrate its own consistency.

Gödel's theorums, in simple terms, say that any sufficiently complex system (non-trivial) cannot prove that it is without flaws.

Software runs on top of hardware, which is also likely to have errors. Even correctly functioning software that encounters a bug at the hardware level will then be classified as failing.


问:
Best way to handle delimited files
So typically a CSV file uses a comma and the return character as it's field and line delimiters.

This runs into obvious problems with text which can contain both these characters.

Obviously there are options there (escaping them) but how do people handle this?  Use different characters - pipes or tildas?  Escape them?  Not use delimited files, after all it's 2010 and we have XML now?

Looking at least effort for a decent chance of not seeing problems.

(Just to be clear, this is a question out of curiosity rather than something more solid - it's something I've come up against time and time again playing with data, always got round it but it normally feels a bit, well, dirty, and wondered what other people's experience was).

答:
Nothing wrong with CSV up to a point

CSV works well for rigidly defined data that is unlikely to change format and doesn't spring many surprises on the recipient parser.

Here's a handy list of the big gotchas:

Escaping ""s within ""s (field contains field delimiter)

""s containing CRLFs (field contains line delimiter)

Unicode (underlying text format may be insufficient)

Different line terminators for different OSes (is CR or CRLF or LF or NUL?)

Inline comments (line prefixed with #, //, --, ; etc)

Version management (the latest version of the file contains more or less fields)

Differentiating between NULL and empty data (,"", is empty but ,, is null?)

You could approach this with a meta-data header that describes how the fields should be parsed, but then you may as well just use XML. It's because of this sort of freeform CSV mess that it was invented. The XML approach just seems too heavyweight for what could, on the face of it, be a simple problem.

A popular alternative is the "weird character delimiter" strategy. This gets around a lot of the escaping issues above because you use something like a | (pipe) character for field delimiting, and a CRLF for record termination. This doesn't get around the multi-line field issue (unless you use a field counter) but you do get nicely formatted lines for humans.

Overall, if you're just looking for a simple way of handling this kind of file then, in the Java world, you could simply throw OpenCSV at it. That way you abstract away all of the problems into an established framework.

Title: Best way to handle delimited files


问:
Why do functional programs have a correlation between compilation success and correctness?
I've been trending toward functional programming for 4 years now, ever since I first started working with LINQ.  Recently, I wrote some pure functional C# code and I noticed, first hand, what I've been reading about functional programs - that once they compile they tend to be correct.

I tried to put a finger on why this is the case but I have not succeeded.

One guess is that in applying OO principals, you have an "abstraction layer" that isn't present in functional programs and this abstraction layer makes it possible for the contracts between objects to be correct while the implementation is wrong.

Has anyone thought about this and come up with the underlying abstract reason for the correlation between compilation success and program correctness in functional programming?

答:
I can write this answer as someone who proves things a lot, so to me correctness isn't just what works, but what works and is easy to prove.

In a lot of senses, functional programming is more restrictive then imperative programming. After all, nothing stops you from never mutating a variable in C! Indeed most of the features in FP languages are straight forward to talk about in terms of only a few core features. It all pretty much boils down to lambdas, function application, and pattern matching!

However, since we've paid the piper in advance, we have a lot less to deal with and we have a lot less options for how things can go wrong. If your a 1984 fan, freedom is indeed slavery! By using 101 different neat tricks for a program, we have to reason about things as though any of these 101 things can happen! That's really hard to do as it turns out :)

If you start with safety scissors instead of a sword, running is moderately less dangerous.

Now we look at your question: how does all of this fit into the "it compiles and works!" phenomena. I think a large part of this is the same reason as why it's easy to prove code! After all, when you write software you're constructing some informal proof that it's correct. Because of this what's covered by your natural handwavy proofs and the compilers own notion of correctness (typechecking) is quite a lot.

As you add features and complicated interactions between them, what's not checked by the type system increases. However, your ability to construct informal proofs doesn't appear to improve! This means that there's more that can slip through your initial inspection and must be caught later.


问:
What is grouping?
In the introduction to K&R there is the following text:

Similarly, C offers only straightforward, single-thread control flow:
  tests, loops, grouping, and subprograms, but not multiprogramming,
  parallel operations, synchronization, or coroutines.

What does grouping refer to? It is not in the index, and searches have been unfruitful so far. I've programmed some C (though I'm far from an expert), and haven't heard the term before.

答:
"C program source text is free-format, using the semicolon as a statement terminator and curly braces for grouping blocks of statements." (Wikipedia)

Blocks don't look like control flow, but they are; without the curly braces only the next line would be controlled by a loop keyword, but with the braces the entire block is looped over.

Title: What is grouping?


问:
Implementation Coupling
This question is regarding Interface Segregation Principle Best-Practices.  I use abstract examples below, but the question arises from actual code I've seen that performs what I can only call "Implementation Coupling".

If I were to break my concrete MilkMan class into his respective roles, I would see that MilkMan has three roles.  He plays the role of a Person (walks and chews bubblegum), He plays the role of a Deliverer (Inventory & Accounting functions?), and He hits on my wife when I'm not at home.

Then when I am writing/reviewing my Accounting logic (or Unit Testing it), I see that some methods in my accounting class(es) can take a MilkMan parameter.  When I see this, I obviously have something wrong.  The only thing my accounting class (Or Unit-Tests of such) cares about is his Deliverer role.

So what I do is identify the roles of my MilkMan, and segregate some interfaces:

IPerson

IDeliverer

ICovetThyW

Now when my accounting class (or its Unit-Tests) needs to mock or pass around Deliverer functionality, the relationships are clear.  I can now have my MailMan, UpsMan, and PoolBoy talk to my Accounting logic by clearly passing around IDeliverer.

So now Unit Testing is much easier to mock, and relationships become more clear in my code.  Everything is great.

What if one method in one implementation is making calls to another method in the same class, but which is part of another implementation?  Take the following code into consideration:

namespace HomeAccounting.KeepAnEyeOnPayments.Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            IDeliverer jose = new MilkMan();
            double paymentAmount = 69;
            if (jose.AcceptPaymentFromCustomer(paymentAmount))
            {
                System.Console.WriteLine("He got " + paymentAmount.ToString());
            }
        }
    }

    public class MilkMan : IPerson, IDeliverer, ICovetThyW
    {
        public bool CanWalk { get; set; }
        public bool CanChewBubblegum { get; set; }

        public bool AcceptPaymentFromCustomer(double amountDue)
        {
            if (GetPaymentFromCustomer(amountDue) == amountDue)
            {
                return true;
            }
            else
            {
                if (AlternativePaymentMethod(amountDue) == amountDue)
                {
                    return true;
                }
            }
            return false;
        }

        private double GetPaymentFromCustomer(double amountDue)
        {
            return 0; //Not willing and/or able to give money.
        }

        public double AlternativePaymentMethod(double amountDue)
        {
            return amountDue;
        }

    }

    public interface IPerson
    {
        bool CanWalk { get; set; }
        bool CanChewBubblegum { get; set; }
    }

    public interface IDeliverer
    {
        bool AcceptPaymentFromCustomer(double amountDue);
    }

    public interface ICovetThyW
    {
        double AlternativePaymentMethod(double amountDue);
    }
}
```

The question is: Does anybody see anything wrong with this?  But in all seriousness: I'd like to know if there is a term or discussion or best-practice listed out there that says you shouldn't be coupling your implementations together.

I want to point out that explicit interface implementation (Which I push for) makes this not even possible to do.  But I've honestly never seen that in a professional environment in 15 years.

答:
I actually think this is one of the major advantages to being able to have a class, that implements multiple interfaces, while having one "implementation". I think the problem is with your example, than with the idea. I remember I did similar solution some time back.

Basically, I created a behavior, that did some work and it required some work before and after it on same files in single folder. To do this, I created two interfaces : IBeforeWork and IAfterWork. The, there was a class, that looked like this:

```<code>public class FileChecker : IBeforeWork, IAfterWork
{
    private string directory;
    private string checksum;

    public FileChecker(string dir)
    {
        this.directory = dir;
    }

    void IBeforeWork.DoWork()
    {
        // calculate checksum from files in directory
    }

    void IAfterWork.DoWork()
    {
        // check checksum on files in directory
    }
}
</code>```

Then, I plugged one instance of this class in both places and had perfectly decoupled checksum checking for files in directory.

Title: Implementation Coupling

Body:
I actually think this is one of the major advantages to being able to have a class, that implements multiple interfaces, while having one "implementation". I think the problem is with your example, than with the idea. I remember I did similar solution some time back.

Basically, I created a behavior, that did some work and it required some work before and after it on same files in single folder. To do this, I created two interfaces : IBeforeWork and IAfterWork. The, there was a class, that looked like this:

public class FileChecker : IBeforeWork, IAfterWork
{
    private string directory;
    private string checksum;

    public FileChecker(string dir)
    {
        this.directory = dir;
    }

    void IBeforeWork.DoWork()
    {
        // calculate checksum from files in directory
    }

    void IAfterWork.DoWork()
    {
        // check checksum on files in directory
    }
}

Then, I plugged one instance of this class in both places and had perfectly decoupled checksum checking for files in directory.