问:
What is the best way to store a formula in a database for a table driven formula?
So I am changing my code over to a table driven formula system to make it sustainable in the long term.

So basically I have 5 foreign keys that will get me to a single formula to use. However I'm not quite sure how I should store the formula. At the moment I am just using a char(100) and parsing it in Java on retrieval. This seems risky though.

My formulas are quite simple (.9 * inputBoxA) but it just gives me a bad feeling doing it this way. Is there a standard for this or will I just have to push on?

Edit:
Let me explain my situation a bit more. I have 5 foreign keys all based on user input. One other input is a rate that the user gives. So based on the 5 FKs I want to do a calculation on this rate.

The formula will usually be (inputRate), (.9*inputRate), etc. But it can get a bit more complex (.9*(.6*inputRate-.1)) but still nothing too bad.

I will be retrieving the formulas from my database with a JPA query and process it in Java so the user should never directly see the formulas. However in the future new formulas may be necessary so I need some standard for others to be able to enter them.

答:
It is a matter of opinion. You might use postfix representation (à la RPN, or even some stack-oriented programming language), or some bytecode (specific to your expression language), or some s-expr syntax, if you want some more compact representation. JSON is probably a less compact textual representation but it is very widely used (and you've got many libraries to parse JSON); you could define your JSON format for your expression ASTs.

You could also store a compressed form of your formula's representation in your database.

You might consider using some bytecode of some existing interpreter, e.g. Lua, Guile2, or even some JVM class with your own class loader, etc...

And perhaps you want to store closures, not expressions.

You may want to embed an interpreter inside your application.

You need to learn more about programming languages (e.g. read Scott's book: Programming Language Pragmatics), compilers (read the dragon book) & parsing & interpreters & semantics ; if you know a bit of Scheme or Lisp (and learning it thru SICP is not a loss of your time) I strongly recommend Queinnec's book Lisp In Small Pieces, giving a broad view of interpretation & compilation techniques.

MathML is a standard for representation of mathematics, notably formulas (using XML). But it is not compact and not easy to parse, so very probably overkill to represent expressions.

OpenDocument is a standard for spreadsheet & word processing documents, so contains a notation for expressions (apparently related to MathML).

You can use some DBMS (from sqlite to PostgresQL, MongoDB, MariaDB/MySQL) to store your formulas (as TEXT or BLOB in SQL sense), you'll be able to store millions or billions of them (e.g. have some SQL TABLE containing them, one row per formula).

Don't forget to document the format of your persistent data, and the form of the "expressions" and/or "closures" in it. Even your advanced users could need to know that format and use it in some other way without having to reverse-engineer it.

Perhaps you are re-inventing business rule management systems or expert systems (look into CLIPS & JESS) or some scripting language (then perhaps try to use an existing one, not invent your own) or spreadsheets ...

I don't see any risk in storing your formulas as text, provided you define and document very well the syntax of your formulas (e.g. using EBNF) and their semantics (e.g. an operational semantics); publish that documentation (advanced users would need to know about them). Parsing efficiently short formulas is not a real issue (the disk I/O or database access would probably be the bottleneck, more than the parsing of the formula) : you can write a simple recursive descent parser or use a parsing expression grammar. Evaluating a formula is more difficult (and requires a semantics, and some evaluation strategy). You'll need some environment to deal with your variables and their binding! Read also about higher-order abstract syntax. Don't forget to validate a formula before storing it.

You might even take a metaprogramming approach and translate these formalas into a routine (or a method, or a class, etc...) or something runnable...


问:
Copyright issues with encryption algorythms
I'm developing an application for Android/Java. This application is a kind of password manager, so I'm storing encrypted passwords under the hood of a master password. There are a number of encryption algorythms DES/AES/BlowFish/TwoFish and so on. My intention is to develop application which is free of commercial copyright issues. So the questions are:

If I use built-in Java encryption API's (e.g. DES/AES)- does it mean that I will be free from possible commercial interests of DES/AES alike copyright holders?

Encryption algorythms sometimes are export limited, keeping in mind that I'm from Moscow/Russia - are there any implications of that fact?

Any other thoughts would be helpful.

答: As stated before, algorithms are not copyrighted, only individual implementations.  Algorithms can be patented, however.  You should read the licensing information for your platform to ensure that you are in the purview of their license grants.  Presuming that you are, in effect, dynamically linking to an encryption library provided by the platform, you would not be distributing any encryption software at all, merely software that makes use of an existing capability.  This may reduce some headaches for you but, as always, you should consult an attorney to get competent answers (and someone to hold accountable if the answers are wrong!).</p>

ContentLicense: CC BY-SA 2.5


问:
Should the story points of stories created after splitting a story add up to the number of story points of that story?
Suppose I have a user story of size 20 that can be split in other 2 user stories, making the original story an epic. Should the sum of these user stories add up to 20? What's the best practice in this case? If they don't add up that could mean in practical terms that the overall complexity of the project changed.</p>

答:
Another factor:  Even if your story points are the infallible word of god a change in the points as you split things up is likely due to roundoff.

Not all 1-point stories are exactly the same size.  You break a 10-point story into 8 equal parts--you have 8 1-point stories but that's because you can't have a 1.25 point story.

ContentLicense: CC BY-SA 3.0


问:
How to maintain an unpopulated 'config' source file in git repo?
Suppose I create some widget, and decide to share it with Github. In this widget project, there's some configuration/preferences file. I need to share what the values being set are, so that if anyone else wished their own widget they'd know what to set. But I don't necessarily want or need to share my own settings.

This would be a case in which some/all of the settings have no concept of a 'default' - they all need to be explicitly set by the programmer.

I thought I was going to find an answer in this question, but really that (or at least it's answers) are more focussed on keeping things secret. I don't need to share in confidence - I just don't need to share.

In essence, I need to deploy Foo := 'Bar', but commit/push/share Foo :=.

What's the best way of handling this in Git?

Some possible solutions:

Commit the unpopulated file; don't include in later commits with preferences set. Disadvantage: if I add a new setting later, need to remove all values to commit it, and then set them again.

Set the values by import/inclusion (as applicable for the language) to ensure an upfront (and less confusing than it might otherwise be) error; clearly state requirements in a readme. Disadvantage: noone likes errors.

Branches? I've never really had the need to use multiple, but I have a feeling the 'right' way to do this might be an un-pushed 'deploy' branch with the values set, and unset in the pushed 'master' branch; just deal with the merge conflicts as they arise on adding new properties? Maybe? Same disadvantage as (1) really, but maybe it's the better practice?

答:
So the idea is: If I check out your git repository, I get a config file template, where I need to fill in the proper values, and you cannot know what the correct values would be for me. In that case, your config file should obviously have plenty of documentation, and building / running the project should fail as early as possible for me if I don't make the necessary changes. It should also be hard for me to commit my fixed config file so it doesn't get distributed by accident (for the same reason that you don't commit your actual config file). </p>

<p>I'd check in a template file, make sure that the whole project is set up so that the template file doesn't become part of the build, and add instructions for me how to create the correct config file, and setup your project so that the correct config file is needed to build. You can else setup git so that it will ignore the config file. </p>

Body:
So the idea is: If I check out your git repository, I get a config file template, where I need to fill in the proper values, and you cannot know what the correct values would be for me. In that case, your config file should obviously have plenty of documentation, and building / running the project should fail as early as possible for me if I don't make the necessary changes. It should also be hard for me to commit my fixed config file so it doesn't get distributed by accident (for the same reason that you don't commit your actual config file).

I'd check in a template file, make sure that the whole project is set up so that the template file doesn't become part of the build, and add instructions for me how to create the correct config file, and setup your project so that the correct config file is needed to build. You can else setup git so that it will ignore the config file.


问:
How do you use exit status code?
When the program run successfully, usually the program will return 0 status. If there any problems, the we can return value other than 0 at exit. With Exceptions, (as long as the problem is not undefined behaviour), we can return 0 value even though program is unsuccessfully finished.

My questions is:

Is the status code used to identify what problem that occured?
Maybe for tracking bugs or documentation purpose?

Is exception have to return status code other than 0 or is it
bad to return non 0 exit code?

How do you decide which status code to be returned? Can I return
the same status code for different errors?

Generally, the question is:

How do you use exit status code?

答:
How exit status codes are used depends for a very large part on what kind of application it is. The main use of exit status codes is when you want to automate the execution of applications using scripting.

If the application is an interactive application, where the expectation is that the user always directly interacts with the application, then exit status codes are largely ignored. There is never an (automated) decision to make what to do next depending on how the application exited.

If the application is designed to be interactive, but also has a 'batch' mode for occasional running in a script, then the application will usually indicate either success or failure, like a boolean status code.

If the designers of the application really had scripting on their mind, then they probably have added multiple exit status codes for different kinds of failure, so that script authors can react accordingly. These are user-level errors and will typically map to one or more internal error situations.

Title: How do you use exit status code?


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
That particular expression makes my eyes hurt; I'd lash out an any developer on my team that used it because it's unmaintainable.

Ternary operators are not evil when used well. They don't even have to be single lines; A long one that is formatted well can be very clear and easy to understand:

```<code>return
      ( 'a' == $s ) ? 1
    : ( 'b' == $s ) ? 2
    : ( 'c' == $s ) ? 3
    :                 4;
</code>```

I like that better than the equivalent if/then/else chain:

```<code>if ( 'a' == $s ) {
    $retval = 1;
}
elsif ( 'b' == $s ) {
    $retval = 2;
}
elsif ( 'c' == $s ) {
    $retval = 3;
}
else {
    $retval = 4;
}

return $retval;
</code>```

I'll reformat those into:

```<code>if    ( 'a' == $s ) { $retval = 1; }
elsif ( 'b' == $s ) { $retval = 2; }
elsif ( 'c' == $s ) { $retval = 3; }
else                { $retval = 4; }

return $retval;
</code>```

if the conditions and assignments allow easy alignment. Still I prefer the ternary version because it's shorter and doesn't have as much noise around the conditions and assignments.

Title: Ternary operator considered harmful?

Body:
That particular expression makes my eyes hurt; I'd lash out an any developer on my team that used it because it's unmaintainable.

Ternary operators are not evil when used well. They don't even have to be single lines; A long one that is formatted well can be very clear and easy to understand:

return
      ( 'a' == $s ) ? 1
    : ( 'b' == $s ) ? 2
    : ( 'c' == $s ) ? 3
    :                 4;

I like that better than the equivalent if/then/else chain:

if ( 'a' == $s ) {
    $retval = 1;
}
elsif ( 'b' == $s ) {
    $retval = 2;
}
elsif ( 'c' == $s ) {
    $retval = 3;
}
else {
    $retval = 4;
}

return $retval;

I'll reformat those into:

if    ( 'a' == $s ) { $retval = 1; }
elsif ( 'b' == $s ) { $retval = 2; }
elsif ( 'c' == $s ) { $retval = 3; }
else                { $retval = 4; }

return $retval;

if the conditions and assignments allow easy alignment. Still I prefer the ternary version because it's shorter and doesn't have as much noise around the conditions and assignments.


问:
Hyperlinked, externalized source code documentation
Why do we still embed natural language descriptions of source code (i.e., the reason why a line of code was written) within the source code, rather than as a separate document?

Given the expansive real-estate afforded to modern development environments (high-resolution monitors, dual-monitors, etc.), an IDE could provide semi-lock-step panels wherein source code is visually separated from -- but intrinsically linked to -- its corresponding comments. For example, developers could write source code comments in a hyper-linked markup language (linking to additional software requirements), which would simultaneously prevent documentation from cluttering the source code.

What shortcomings would inhibit such a software development mechanism?

A mock-up to help clarify the question:

When the cursor is at a particular line in the source code (shown with a blue background, above), the documentation that corresponds to the line at the cursor is highlighted (i.e., distinguished from the other details). As noted in the question, the documentation would stay in lock-step with the source code as the cursor jumps through the source code. A hot-key could switch between "documentation mode" and "development mode".

Potential advantages include:

More source code and more documentation on the screen(s) at once

Ability to edit documentation independently of source code (regardless of language?)

Write documentation and source code in parallel without merge conflicts

Real-time hyperlinked documentation with superior text formatting

Quasi-real-time machine translation into different natural languages

Every line of code can be clearly linked to a task, business requirement, etc.

Documentation could automatically timestamp when each line of code was written (metrics)

Dynamic inclusion of architecture diagrams, images to explain relations, etc.

Single-source documentation (e.g., tag code snippets for user manual inclusion).

Note:

The documentation window can be collapsed

Workflow for viewing or comparing source files would not be affected

How the implementation happens is a detail; the documentation could be:

kept at the end of the source file;

split into two files by convention (filename.c, filename.c.doc); or

fully database-driven

By hyperlinked documentation, I mean linking to external sources (such as StackOverflow or Wikipedia) and internal documents (i.e., a wiki on a subdomain that could cross-reference business requirements documentation) and other source files (similar to JavaDocs).

Related thread: What's with the aversion to documentation in the industry?

答:
Source code and documentation the way it should be done.

http://jasmine.github.io/2.3/introduction.html


问:
What is the difference between currying and partial function application in practice
I understand the difference between partial function application and a curried function (f(X x Y x Z) -> N vs f(X -> (Y -> (Z -> N)))), but I do not see what the consequence of this difference is when developing software.

答:
Originally, currying was to simplify analysis, rather than a practical programming technique; in lambda calculus, all functions are unary. Currying is often used at the language level for a similar reason: simplifying the computational model.

Partial application is used when a named, useful function can be implemented in terms of another, more general function simply by fixing an argument.

They remain distinct forms, involving different parts of computation. Consider:

```<code>x=>y=>z=>f(x,y)
(y,z)=>f(0,y,z)
</code>```

Note that a curried function doesn't have any values bound to arguments and takes the arguments in a specific order; once you curry a function, you don't curry the result and don't change the order that the function takes arguments (though you could uncurry and curry to do so). A partial function, in contrast, has values bound to arguments and can be further partially applied along any remaining argument.

Applying a curried function is close to partial application (you don't, after all, curry a function and leave it at that; at some point, you're going to apply it), which is where uses begin to cross over. When you do this, currying is only the first of two steps towards partial application.

Body:
Originally, currying was to simplify analysis, rather than a practical programming technique; in lambda calculus, all functions are unary. Currying is often used at the language level for a similar reason: simplifying the computational model.

Partial application is used when a named, useful function can be implemented in terms of another, more general function simply by fixing an argument.

They remain distinct forms, involving different parts of computation. Consider:

x=>y=>z=>f(x,y)
(y,z)=>f(0,y,z)

Note that a curried function doesn't have any values bound to arguments and takes the arguments in a specific order; once you curry a function, you don't curry the result and don't change the order that the function takes arguments (though you could uncurry and curry to do so). A partial function, in contrast, has values bound to arguments and can be further partially applied along any remaining argument.

Applying a curried function is close to partial application (you don't, after all, curry a function and leave it at that; at some point, you're going to apply it), which is where uses begin to cross over. When you do this, currying is only the first of two steps towards partial application.


答:
I believe that your question can be rephrased as: why do languages have currying?

It is mostly a question of convenience:

In Ocaml, you could code

```<code> let sum3 x y z = x + y + z;;
 let foo xx yy ll = List.map (sum3 xx yy) ll;;
</code>```

In Scheme you'll need to explicitly make an anonymous function

```<code> (define (sum3 x y z) (+ x y z))
 (define (foo xx yy ll) (map (lambda (zz) (sum3 xx yy zz)) ll))
</code>```

Languages with partial applications & currying need practically to have an optimization to avoid creating partial closures everywhere; you don't want the implementation to always apply sum3 as if it was defined as

```<code> let sum3 x =
    fun y ->
      (fun z -> x + y + z)
</code>```

that is, to allocate 2 intermediate closures when computing sum3 1 2 3 (understood and parsed as ((sum3 1) 2) 3 ...). You want the sum to be computed immediately.

Title: What is the difference between currying and partial function application in practice

Body: I understand the difference between partial function application and a curried function (f(X x Y x Z) -> N vs f(X -> (Y -> (Z -> N)))), but I do not see what the consequence of this difference is when developing software.

Body:
I believe that your question can be rephrased as: why do languages have currying?

It is mostly a question of convenience:

In Ocaml, you could code

 let sum3 x y z = x + y + z;;
 let foo xx yy ll = List.map (sum3 xx yy) ll;;

In Scheme you'll need to explicitly make an anonymous function

 (define (sum3 x y z) (+ x y z))
 (define (foo xx yy ll) (map (lambda (zz) (sum3 xx yy zz)) ll))

Languages with partial applications & currying need practically to have an optimization to avoid creating partial closures everywhere; you don't want the implementation to always apply sum3 as if it was defined as

 let sum3 x =
    fun y ->
      (fun z -> x + y + z)

that is, to allocate 2 intermediate closures when computing sum3 1 2 3 (understood and parsed as ((sum3 1) 2) 3 ...). You want the sum to be computed immediately.


问:
Is there a standard way to indicate that a function returns a new pointer?
Sometimes I want to delegate the construction of objects that a class owns to a separate function. Something like

```<code>Vertex* new_vertex(const Options& options) {
  // do stuff...
  return new Vertex(...);
}
</code>```

where the function is only intended to be used to within a class that owns the Vertex. Clearly this function can cause some memory-leaking confusion, so I want to make it as clear as possible. Is there a naming convention for such functions?

答:
Is there a standard way to indicate that a function returns a new pointer?

No, there is no "standard way" (but there is an API design policy currently considered "best practice").

Because of this ambiguity ("what does a function returning a pointer want me to do with it?"), it is currently considered best practice to impose the lifetime and ownership policy, through the return type:

```<code><vertex pointer type> new_vertex(const Options& options);
</code>```

<vertex pointer type> can be std::unique_ptr ("new_vertex doesn't own the pointer"), or std::shared_ptr ("client code doesn't own the pointer"), or something else, that has clearly defined ownership semantics (for example, Vertex const * const would indicate to client code "read the address and values, but change neither/don't delete the pointer").

Generally, you should not return a raw pointer (but in some cases, "practicality beats purity").

TLDR: there is a best practice (yes), but not a standard way (in the language).

Edit:

where the function is only intended to be used to within a class that owns the Vertex

If the class owns the Vertex, I would write it like this:

```<code>class SomeClass // owns the vertex
{
    void do_stuff() // uses the vertex internally
    {
        init_vertex(); // see below
        assert(vertex.get());
        // use vertex as needed
    }
private:
    // "class owns the Vertex"
    std::unique_ptr<Vertex> vertex;

    // sets the internal vertex
    // function doesn't return a pointer of any kind
    void init_vertex(const Options& options); // or "reset_", "refresh_",
                                              // or "make_" vertex,
                                              // if the pointer can change
                                              // throughout the lifetime
                                              // of a SomeClass instance
};
</code>```

Body:
Is there a standard way to indicate that a function returns a new pointer?

No, there is no "standard way" (but there is an API design policy currently considered "best practice").

Because of this ambiguity ("what does a function returning a pointer want me to do with it?"), it is currently considered best practice to impose the lifetime and ownership policy, through the return type:

<vertex pointer type> new_vertex(const Options& options);

<vertex pointer type> can be std::unique_ptr ("new_vertex doesn't own the pointer"), or std::shared_ptr ("client code doesn't own the pointer"), or something else, that has clearly defined ownership semantics (for example, Vertex const * const would indicate to client code "read the address and values, but change neither/don't delete the pointer").

Generally, you should not return a raw pointer (but in some cases, "practicality beats purity").

TLDR: there is a best practice (yes), but not a standard way (in the language).

Edit:

where the function is only intended to be used to within a class that owns the Vertex

If the class owns the Vertex, I would write it like this:

class SomeClass // owns the vertex
{
    void do_stuff() // uses the vertex internally
    {
        init_vertex(); // see below
        assert(vertex.get());
        // use vertex as needed
    }
private:
    // "class owns the Vertex"
    std::unique_ptr<Vertex> vertex;

    // sets the internal vertex
    // function doesn't return a pointer of any kind
    void init_vertex(const Options& options); // or "reset_", "refresh_",
                                              // or "make_" vertex,
                                              // if the pointer can change
                                              // throughout the lifetime
                                              // of a SomeClass instance
};


答:
Exceptions and exit status codes are two very different things. Exceptions are at the scope of the application; exit status codes are at the scope of the operating system.

When an application calls another one, basically, the only standard way for it to determine that the callee finished successfully is the exit status code. 0 means success. Anything else means failure. The fact that there is no standard for which code is which means that determining the source of the failure often requires to do an additional step of browsing the documentation, when available. Given the vast diversity of issues, creating such standard would be both practically and theoretically impossible: even if you can standardize some errors, such as "file not found", an exit code, that is a simple number, won't be detailed enough: in a case of a file not being found, which file exactly was expected?

This flaw is exactly the same as the one which pushed to abandon error codes within a program and use exceptions instead.

Exceptions:

Are often explicit, as they contain the type, the summary and additional data. The type FileNotFoundException coupled with the path of the expected file and the stack trace helps identifying very precisely the problem, both as a user of a program and as a programmer—if it's the fault of the program for being unable to find the file or not being able to fallback to another option.

Can be caught within the application itself.

When it comes to inter-process communication, web services, for example, make it possible to emulate at least the first benefit of the exceptions, by providing JSON/XML representation of an error, rather than just a error code.

Title: How do you use exit status code?

Body:
When the program run successfully, usually the program will return 0 status. If there any problems, the we can return value other than 0 at exit. With Exceptions, (as long as the problem is not undefined behaviour), we can return 0 value even though program is unsuccessfully finished.

My questions is:

Is the status code used to identify what problem that occured?
Maybe for tracking bugs or documentation purpose?

Is exception have to return status code other than 0 or is it
bad to return non 0 exit code?

How do you decide which status code to be returned? Can I return
the same status code for different errors?

Generally, the question is:

How do you use exit status code?


答:
Exit codes are operating system specific. In C99, <stdlib.h> knows about exit(3) and EXIT_SUCCESS & EXIT_FAILURE. I'm focusing on Linux.

POSIX and Linux systems accept 256 different values to exit, with 0 being EXIT_SUCCESS and other non-zero values (1 to 255) for some kind of failures.

BSD has attempted to standardize exit codes; see the file <sysexits.h>

You might have several exit codes (e.g. a dozen different of them). Don't forget to document them.

The waitpid(2) syscall can retrieve the exit code of a forked child process, and the status is also returned by system(3)

Exceptions ought to be caught and handled, at least by the runtime system (e.g. on C++ or Java or Ocaml).

Some programs are registering functions with atexit(3) and some daemons or servers are handling SIGTERM signal (see signal(7)), this is why on Linux it is not advisable to kill(2) processes with SIGKILL (you should try SIGTERM then SIGQUIT before the unhandable SIGKILL, to let a well behaved program clean its mess before termination, e.g. let some database manager flush its state to disk).

Title: How do you use exit status code?


答:
In a shell program you can use them to make some decisions. In bash <code>$?</code> is the variable which holds the status of the last program that exited. </p>

```<code>if [$? -eq 0 ]; then
   echo "Everything is okay"
else
   echo "Something is terribly wrong!"
fi
</code>```

Title: How do you use exit status code?

Body:
In a shell program you can use them to make some decisions. In bash $? is the variable which holds the status of the last program that exited.

if [$? -eq 0 ]; then
   echo "Everything is okay"
else
   echo "Something is terribly wrong!"
fi


问:
What is the connection between messages in sequence diagrams and method calls?
Since sequence diagrams depict messages between objects in a system, the messages have to be representing method calls. My question is if I have two objects in the diagram lifeline

A --- doSomething(parameters) --> B

which object is invoking the method?

Is A calling its method doSomething which in turn uses B in its implementation?
Or is A sending a message to B and B is the actual object that invokes the doSomething method?

答:
A is sending the message doSomething(parameters) to B

or

A is calling doSomething(parameters) on B

both are equivalent. I think it was when “they” where factoring eval and/or apply in scheme (lisp) that “they” realised that message passing and method calls are the same thing.

Therefore the 2nd of your 2 options.


答:
Is A calling its method doSomething which in turn uses B in its implementation? Or is A sending a message to B and B is the actual object that invokes the doSomething method?

A is calling doSomething on B.

How that happens is an implementation detail.

It could be a direct function call, where A is calling the method on B, or it could be a message, e.g. RPC, through a network, where A is requesting B to execute the method and return the result. It could even be A calling it's own function which then is calling B, if it is not doing something else important in the process.

What's important to understand is that a sequence diagram is an abstraction that shows who is doing what when. It's not so much about the details how that happens. It is not trying to write the code for you.

So if it is important that A is calling itself, that would be in the sequence diagram. But if A is calling itself only to call B, that would likely be abstracted away into A calls B.

Title: What is the connection between messages in sequence diagrams and method calls?

Body:
Since sequence diagrams depict messages between objects in a system, the messages have to be representing method calls. My question is if I have two objects in the diagram lifeline

A --- doSomething(parameters) --> B

which object is invoking the method?

Is A calling its method doSomething which in turn uses B in its implementation?
Or is A sending a message to B and B is the actual object that invokes the doSomething method?


答:
"Calling a method" and "sending a message" are simply two terms from two different communities for the same thing.

When Alan Kay came up with the term "Object Orientation", he was heavily inspired by what would later become the ARPANet and then the Internet: independent machines ("objects") with their own private memory ("instance variables") that communicate with each other by sending messages.

So, in the lingo of Smalltalk and its successors, derivatives and cousins (Self, Ruby, Python, ECMAScript/JavaScript, Objective-C, Java, …) objects send messages to other objects and those objects then "respond" to that message however they see fit. The most popular reaction is to invoke a method of the same name (i.e. if you send the message foo to bar, the result will be that the foo method of bar will be invoked), but an object may also forward the message to another object or respond with a pre-calculated value (instance variable), or just blatantly ignore it.

In the lingo of Simula and its family, this is called "calling a method" and the process of deciding what to do in response is called "virtual dispatch. In the C++ family, it is called "calling a virtual function" and "vtable lookup".

But it's all more or less the same.

Personally, I prefer the messaging metaphor, because it highlights encapsulation (when you send a message to someone, you have no idea what he does with the message, the only thing you can observe is the reply), and because it evokes the analogies of handing the message off to someone else etc.


问:
Does ShareAlike mean, that if I include a resource released under CC-BY-SA in my program, that I have to release my entire code?
The FAQ states:

ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.

That makes sense -  if I want to include a graphic under that license and modify it, then I have to make that modification publicly available under the same license.
But does that apply to the rest of my code? Whether or not I include a modified or the original graphic in my application?

I have no issue with attribution or releasing my modifications of affected graphics, but I don't want to publish my code.

答:
The basic question is: does your code, or the creation of it, in any way rely on that particular image.

If you somehow derived your code from the image, then your code would be a derived work and you would have to publish your code under the CC-BY-SA license.

However, and this is more usual, if the image is just something that gets displayed in the context of our application, but it could just as easily have been a completely different picture under a different license, then the two are not related as far as copyright is concerned and the CC-BY-SA license of the picture doesn't affect your code.


答: IANAL. My take: You are only using what already exists on the platform. There can't be a copyright issue or patent issue or export issue for something that will be on the device whether or not your software is installed.</p>

Title: Copyright issues with encryption algorythms

Body:
I'm developing an application for Android/Java. This application is a kind of password manager, so I'm storing encrypted passwords under the hood of a master password. There are a number of encryption algorythms DES/AES/BlowFish/TwoFish and so on. My intention is to develop application which is free of commercial copyright issues. So the questions are:

If I use built-in Java encryption API's (e.g. DES/AES)- does it mean that I will be free from possible commercial interests of DES/AES alike copyright holders?

Encryption algorythms sometimes are export limited, keeping in mind that I'm from Moscow/Russia - are there any implications of that fact?

Any other thoughts would be helpful.


问:
What is ¬ called and what is it for?
Googling this question has proved somewhat useless, so the ¬ symbol:

What is it for?

What is is called?

Is it used in any programming languages?

答:
The only use I've seen for the ¬ symbol is to represent negation in the context of formal logic. For instance, if P is the proposition "It will rain today", then ¬P is the proposition "It will not rain today." I've also seen ~ used for this.

I don't believe it has an actual name other than "negation symbol". Normally it's read as "not".

As far as I know, in programming this symbol has no special meaning, at least not in any mainstream languages I've used.

Title: What is ¬ called and what is it for?


问:
Ways to do callback, when and where
I've recently started to do some more complicated programming with network-related work on iOS with Swift.
This introduced a lot of asynchronous code not only in networking but also some exchange of information between view controllers.

Anyway, my question is simple, and can be quite general. As far as I know, there are (at least) four ways to do callback, so is there a general rule as to which is better in each case?

callback closure (function) as a function argument

delegation with protocol

notification (or observer)

shared state object

Use cases in my application

Network stuff, POST request or download file

passing data one-way between view controllers on button tap

passing data both-ways between view controllers
(One view shows the selected option, another view gives the real options for user to select)

答:
Here are my views on the various observation patterns. I may update this list over time if comments seem to require it.

Callback with closure: This is great if you have some sort of
one-shot thing (like a network response), or multiple responses that all need to be handled the same way. Not so good if you are expecting multiple responses which need to be handled differently or different types of
responses (which would require a different closure for each type of
response.) Also not helpful if you have multiple objects interested
in the response.

Delegation with protocol: Makes a lot of sense if there is a
business reason why there should only be one listener/observer and
it makes sense for that observer to handle several different state
changes. In other words, if you have more than one object that is
interested in the subject, then delegation won't work. If you end up
with a protocol that only forces the implementation of one method,
then this pattern is likely not a good idea either. Also, if you
have an observer that wants to track several different objects that
implement the protocol in question, then you should probably
reconsider the use of this pattern.

Notification: The NSNotificationCenter works pretty well for very
generic or system wide messages. If you only have one observer, or
only expect the message to be sent once, then this is a poor choice
of pattern. Also, this pattern can save you a lot of refactoring
when you have to send a message between two disparate objects in a
mature system (i.e., a hack.)

Key value Observation: This works well if the observer only wants to
monitor the state of a single field but can get unwieldy if trying
to observe several fields or if you just want to be informed of some
signal.

Some patterns you didn't mention:

target/action callback: An example of this is UIControl... This has
the same benefits and tradeoffs as a callback with closure and I
think has largely been superseded by it.

Abstract method/subclass instantiation: There is the classic mode of
implementing a method in a subclass to handle requirements of the
base class. UIViewController's viewDidLoad and the like are
examples. Another pattern that has been largely superseded, by
protocols, but comes in handy if you happen to already have the
class structure in place.

Futures/Promises: This pattern has the same benefits and drawbacks as callback closures, but can avoid nested closures that sometimes pop-up.

Lastly, there is reactive programming (ReactiveCocoa and RxSwift for example) that can potentially take the place of all of the above patterns. It takes some time to learn but once you get the hang of it, you can handle all your observation needs with one pattern.

Title: Ways to do callback, when and where


问:
Is the time complexity of a while loop with three pointers different than 3 nested for loops?
This program (written in ruby) finds the largest 3 numbers in an array (without sorting the array). It has a while loop with three pointers. My fist instinct, since there is only one loop is to say this solution is O(n). But, the pointer's j and k get reset when they reach n which seems the same as  using 3 for loops, so then is it O(n³)?

```<code>def greatest_of_3_with_ptrs(a)
  greatest = 0
  greatest_tuple = nil
  i,j,k=0,1,2
  n = a.length-1
  while( true) do
    sum = a[i]+a[j]+a[k]
    if sum > greatest then
      greatest = sum
      greatest_tuple =[a[i],a[j],a[k]]
    end
    sum = 0
    if k == n then
      j=j+1
      k=j+1
    else
      k+=1
    end
    if j == n then
      i=i+1
      j=i+1
      k=j+1
    end
    break if k > n || j > n || i==n
  end
  { greatest_tuple: greatest_tuple, greatest: greatest }
end

a =[10,-1,4,2,5,3,0]
expected = 19
print greatest_of_3_ptrs(a)[:greatest] #> 19
print greatest_of_3_ptrs(a)[:greatest_tuple] #> [10,4,5]
</code>```

Please Note: I am aware of the O(n) solution, that is not my question

```<code>def greatest(a)
  max_1,max_2,max_3 = a[0],a[1],a[2]
  for i in 3..a.length-1
    if a[i] > max_1 then
      max_1 = a[i]
    elsif a[i] > max_2 then
      max_2 = a[i]
    elsif a[i] > max_3 then
      max_3 = a[i]
    end
  end
  [max_1,max_2,max_3]
end
</code>```

答:
If looks like a O(n³) solution. Your instinct is correct: by resetting variables you are looping. Note: if we only consider the loop instruction we would, mistakenly, think it was O(∞).

However the problem is O(n). Therefore you can do better.


答:
If you create you program so that it loads the image at run-time (it is not linked): the user of the program must be able to change the image (customisation), if not then it is linked. Then the program should not be affected, it would be like an image viewer, it is not affected by the images that it views.

I am not a lawyer. Please read the licence, and applicable laws carefully and consult your legal department.

Title: Does ShareAlike mean, that if I include a resource released under CC-BY-SA in my program, that I have to release my entire code?

Body:
The FAQ states:

ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original.

That makes sense -  if I want to include a graphic under that license and modify it, then I have to make that modification publicly available under the same license.
But does that apply to the rest of my code? Whether or not I include a modified or the original graphic in my application?

I have no issue with attribution or releasing my modifications of affected graphics, but I don't want to publish my code.


问:
rand() gives same numbers again for a small range
I'm trying to make sort of a game where I have a a grid of 20x20 and I display a player (P), a target (T) and three enemies (X). All these have an X and a Y coordinate which are assigned using rand(). The problem is that if I try to get more points in the game (refills for energy etc) they overlap with one or more of the other points because the range is small(1 to 20 inclusive).

These are my variables and how I'm assigning them values:
(the COORD is a struct with just an X and a Y)

```<code>const int gridSize = 20;
COORD player;
COORD target;
COORD enemy1;
COORD enemy2;
COORD enemy3;

//generate player
srand ( time ( NULL ) );
spawn(&player);
//generate target
spawn(&target);
//generate enemies
spawn(&enemy1);
spawn(&enemy2);
spawn(&enemy3);

void spawn(COORD *point)
{
    //allot X and Y coordinate to a point
    point->X = randNum();
    point->Y = randNum();
}

int randNum()
{
    //generate a random number between 1 and gridSize
    return (rand() % gridSize) + 1;
}
</code>```

I want to add more things to the game but the probability of overlap increases when I do that. Is there any way to fix this?

答:
Pertaining to rand() % n being less than ideal

Doing rand() % n has a non-uniform distribution.  You will get a disproportionate number of certain values because the number of values isn't a multiple of 20

Next, rand() is typically a linear congruential generator (there are many others, just this is the most likely one implemented - and with less than ideal parameters (there are many ways to select the parameters)). The biggest problem with this is that often the low bits in it (the ones you get with a % 20 type expression) are not that random. I recall one rand() from years ago where the lowest bit alternated from 1 to 0 with each call to rand() -- it wasn't very random.

From rand(3) man page:

```The  versions of rand() and srand() in the Linux C Library use the same
random number generator as random() and srandom(), so  the  lower-order
bits  should  be as random as the higher-order bits.  However, on older
rand() implementations, and on  current implementations  on  different
systems,  the  lower-order  bits  are much less random than the higher-
order bits.  Do not use this function in applications  intended to  be
portable when good randomness is needed.```

This may be now relegated to history, but it is quite possible that you've still got a poor rand() implementation hiding down somewhere in the stack. In which case, its still quite applicable.

The thing to do is to actually use a good random number library (that gives good random numbers) and then ask for random numbers within the range you want.

An example of a good random number bit of code (from 13:00 in the linked video)

```<code>#include <iostream>
#include <random>
int main() {
    std::mt19937 mt(1729); // yes, this is a fixed seed
    std::uniform_int_distribution<int> dist(0, 99);
    for (int i = 0; i < 10000; i++) {
        std::cout << dist(mt) << " ";
    }
    std::cout << std::endl;
}
</code>```

Compare this to:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    srand(time(NULL));
    for (int i = 0; i < 10000; i++) {
        printf("%d ", rand() % 100);
    }
    printf("\n");
}
</code>```

Run both of these programs and compare how often certain numbers come up (or don't come up) in that output.

Related video: rand() considered harmful

Some historical aspects of rand() causing bugs in Nethack that one should watch and consider in one's own implementations:

Nethack RNG Problem

Rand() is a very fundamental function for Nethack's random number generation. The way Nethack uses it is buggy or it may be argued that lrand48() produces crappy pseudo-random numbers. (However, lrand48() is a library function using a defined PRNG method and any program that uses it should take into account the weaknesses of that method.)

The bug is that Nethack relies (sometimes exclusively as is the case in rn(2)) on the lower bits of the results from lrand48(). Because of this, RNG in the whole game works bad. This is especially noticable before user actions introduce further randomness, i.e. in character generation and first level creation.

While the above was from 2003, it should still be kept in mind as it may not be the case that all of the systems running your intended game will be an up to date Linux system with a good rand() function.

If you are just doing this for yourself, you can test how good your random number generator is by writing some code and testing the output with ent.

On the properties of random numbers

There are other interpretations of 'random' that aren't exactly random. In a random stream of data, it is quite possible to get the same number twice. If you flip a coin (random), it is quite possible to get two heads in a row. Or throw a dice twice and get the same number twice in a row. Or spinning a roulette wheel and getting the same number twice there.

The distribution of numbers

When playing a song list, people expect 'random' to mean that the same song or artist won't be played a second time in a row. Having a playlist play The Beatles twice in a row is considered 'not random' (though it is random).  The perception that for a play list of four songs played a total of eight times:

```<code>1 3 2 4 1 2 4 3
</code>```

is more 'random' than:

```<code>1 3 3 2 1 4 4 2
</code>```

More on this for the 'shuffling' of songs: How to shuffle songs?

On repeated values

If you don't want to repeat values, there is a different approach that should be considered.  Generate all the possible values, and shuffle them.

If you are calling rand() (or any other random number generator), you are calling it with replacement. You can always get the same number twice. One option is to toss out the values again and again until you select one that meets your requirements.  I will point out that this has a non-determistic runtime and it is possible that you could find yourself in a situation where there is an infinite loop unless you start doing a more complex back tracing.

List and Pick

Another option is to generate a list of all possible valid states and then select a random element from that list.  Find all the empty spots (that meet some rules) in the room and then pick a random one from that list. And then do it again and again until you're done.

Shuffle

The other approach is to shuffle as if it was a deck of cards. Start out with all the empty spots in the room and then start assigning them by dealing out the empty spots, one at a time, to each rule/process asking for an empty spot. You are done when you run out of cards or things stop asking for them.

Body:
Pertaining to rand() % n being less than ideal

Doing rand() % n has a non-uniform distribution.  You will get a disproportionate number of certain values because the number of values isn't a multiple of 20

Next, rand() is typically a linear congruential generator (there are many others, just this is the most likely one implemented - and with less than ideal parameters (there are many ways to select the parameters)). The biggest problem with this is that often the low bits in it (the ones you get with a % 20 type expression) are not that random. I recall one rand() from years ago where the lowest bit alternated from 1 to 0 with each call to rand() -- it wasn't very random.

From rand(3) man page:

The  versions of rand() and srand() in the Linux C Library use the same
random number generator as random() and srandom(), so  the  lower-order
bits  should  be as random as the higher-order bits.  However, on older
rand() implementations, and on  current implementations  on  different
systems,  the  lower-order  bits  are much less random than the higher-
order bits.  Do not use this function in applications  intended to  be
portable when good randomness is needed.

This may be now relegated to history, but it is quite possible that you've still got a poor rand() implementation hiding down somewhere in the stack. In which case, its still quite applicable.

The thing to do is to actually use a good random number library (that gives good random numbers) and then ask for random numbers within the range you want.

An example of a good random number bit of code (from 13:00 in the linked video)

#include <iostream>
#include <random>
int main() {
    std::mt19937 mt(1729); // yes, this is a fixed seed
    std::uniform_int_distribution<int> dist(0, 99);
    for (int i = 0; i < 10000; i++) {
        std::cout << dist(mt) << " ";
    }
    std::cout << std::endl;
}

Compare this to:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
    srand(time(NULL));
    for (int i = 0; i < 10000; i++) {
        printf("%d ", rand() % 100);
    }
    printf("\n");
}

Run both of these programs and compare how often certain numbers come up (or don't come up) in that output.

Related video: rand() considered harmful

Some historical aspects of rand() causing bugs in Nethack that one should watch and consider in one's own implementations:

Nethack RNG Problem

Rand() is a very fundamental function for Nethack's random number generation. The way Nethack uses it is buggy or it may be argued that lrand48() produces crappy pseudo-random numbers. (However, lrand48() is a library function using a defined PRNG method and any program that uses it should take into account the weaknesses of that method.)

The bug is that Nethack relies (sometimes exclusively as is the case in rn(2)) on the lower bits of the results from lrand48(). Because of this, RNG in the whole game works bad. This is especially noticable before user actions introduce further randomness, i.e. in character generation and first level creation.

While the above was from 2003, it should still be kept in mind as it may not be the case that all of the systems running your intended game will be an up to date Linux system with a good rand() function.

If you are just doing this for yourself, you can test how good your random number generator is by writing some code and testing the output with ent.

On the properties of random numbers

There are other interpretations of 'random' that aren't exactly random. In a random stream of data, it is quite possible to get the same number twice. If you flip a coin (random), it is quite possible to get two heads in a row. Or throw a dice twice and get the same number twice in a row. Or spinning a roulette wheel and getting the same number twice there.

The distribution of numbers

When playing a song list, people expect 'random' to mean that the same song or artist won't be played a second time in a row. Having a playlist play The Beatles twice in a row is considered 'not random' (though it is random).  The perception that for a play list of four songs played a total of eight times:

1 3 2 4 1 2 4 3

is more 'random' than:

1 3 3 2 1 4 4 2

More on this for the 'shuffling' of songs: How to shuffle songs?

On repeated values

If you don't want to repeat values, there is a different approach that should be considered.  Generate all the possible values, and shuffle them.

If you are calling rand() (or any other random number generator), you are calling it with replacement. You can always get the same number twice. One option is to toss out the values again and again until you select one that meets your requirements.  I will point out that this has a non-determistic runtime and it is possible that you could find yourself in a situation where there is an infinite loop unless you start doing a more complex back tracing.

List and Pick

Another option is to generate a list of all possible valid states and then select a random element from that list.  Find all the empty spots (that meet some rules) in the room and then pick a random one from that list. And then do it again and again until you're done.

Shuffle

The other approach is to shuffle as if it was a deck of cards. Start out with all the empty spots in the room and then start assigning them by dealing out the empty spots, one at a time, to each rule/process asking for an empty spot. You are done when you run out of cards or things stop asking for them.


答:
While the users who complain about rand() and recommend better RNGs are right about the quality of the random numbers, they are also missing the bigger picture. Duplicates in streams of random numbers cannot be avoided, they are a fact of life. This is the lesson of the birthday problem.

On a grid of 20 * 20 = 400 possible spawn positions, a duplicate spawn point is to be expected (50% probability) even when spawning only 24 entities. With 50 entities (still only 12.5% of the whole grid), the probability of a duplicate is over 95%. You have to deal with collisions.

Sometimes you can draw all samples at once, then you can use a shuffle algorithm to draw n guaranteed-distinct items. You just need to generate the list of all possibilities. If the full list of possibilities is too large to store, you can generate spawn positions one at a time as you do now (just with a better RNG) and simply re-generate when a collision occurs. Even though having some collisions is likely, many collisions in a row are exponentially unlikely even if most of the grid is populated.

Title: rand() gives same numbers again for a small range

Body:
I'm trying to make sort of a game where I have a a grid of 20x20 and I display a player (P), a target (T) and three enemies (X). All these have an X and a Y coordinate which are assigned using rand(). The problem is that if I try to get more points in the game (refills for energy etc) they overlap with one or more of the other points because the range is small(1 to 20 inclusive).

These are my variables and how I'm assigning them values:
(the COORD is a struct with just an X and a Y)

```<code>const int gridSize = 20;
COORD player;
COORD target;
COORD enemy1;
COORD enemy2;
COORD enemy3;

//generate player
srand ( time ( NULL ) );
spawn(&player);
//generate target
spawn(&target);
//generate enemies
spawn(&enemy1);
spawn(&enemy2);
spawn(&enemy3);

void spawn(COORD *point)
{
    //allot X and Y coordinate to a point
    point->X = randNum();
    point->Y = randNum();
}

int randNum()
{
    //generate a random number between 1 and gridSize
    return (rand() % gridSize) + 1;
}
</code>```

I want to add more things to the game but the probability of overlap increases when I do that. Is there any way to fix this?


问:
How to compute flow rate of web traffic?
This seems like it should be fairly straight forward but I'm having a devil of a time with it.  Hoping some of you fine folks might be able to lend a hand.

I'm using PHP & MySQL, and want to calculate the flow rates of traffic to certain web pages.  Ultimately I want to be able to send myself alerts when flow rates rise or fall dramatically over certain time periods.  For now I'm thinking I would like to monitor at 5 min, 30min, 60 min, 5 hour, and 24 hour intervals.

The "easy" way to do this would probably be to record every single page request as a separate timestamped entry in my DB and then just count them and do various date diff calculations etc.  But I really don't want to create a new row for every request.  I would rather just increment counters and work off of those, but I'm completely stumped at the moment.

What would be the easiest way to go about this?  My attempts thus far have been so far from the mark that I don't even have any code worth sharing.

答:
If you want to roll your own, instead of storing based on timestamp, you could use the thread id or equivalent and current minute of day to create a unique key composite key and increment the associated value every time you get a request. Then after each minute, you can aggregate all the requests for that minute across all threads to get a utilization value to use in making your decisions.

Alternatively, there are libraries to do this sort of thing.


答:
You're on the right track - each web page request needs to be tracked, but you need to do this is a very simple manner. Then the problem shifts to statistical analysis of these counters, and that's quite easy.

Forget storing each webpage in the DB, instead you need to cache it in memory (as you don't really care about flow rate when the system is restarted) and it'll be much faster to calculate and won't bog down your system writing thousands of counters to the DB.

Don't store the timestamp, instead create a bucket of requests, keep this incremented per minute (which is your minimum granularity), so you have an array of the last 24 hours (1440 entries) with the number of requests each minute stored in each element.

Now you just need to add up the numbers in each of the last n elements, compare them to the current element and if the current number is x over the sum of the others, pop the alert. You could optimise this by performing the sums for the alert periods and storing them in a set of variables every time the minute changes.

Title: How to compute flow rate of web traffic?

Body:
This seems like it should be fairly straight forward but I'm having a devil of a time with it.  Hoping some of you fine folks might be able to lend a hand.

I'm using PHP & MySQL, and want to calculate the flow rates of traffic to certain web pages.  Ultimately I want to be able to send myself alerts when flow rates rise or fall dramatically over certain time periods.  For now I'm thinking I would like to monitor at 5 min, 30min, 60 min, 5 hour, and 24 hour intervals.

The "easy" way to do this would probably be to record every single page request as a separate timestamped entry in my DB and then just count them and do various date diff calculations etc.  But I really don't want to create a new row for every request.  I would rather just increment counters and work off of those, but I'm completely stumped at the moment.

What would be the easiest way to go about this?  My attempts thus far have been so far from the mark that I don't even have any code worth sharing.


问:
Why does scala require parenthesis around the condition of an if statement
Just curious, from a syntax parsing perspective, why does Scala actually require parentheses around the condition of an if statement, given that the only thing allowed after if is (?

答:
The parentheses don't only delimit where the condition starts; they also indicate where it ends.

You're right that technically, only the right parenthesis is necessary to resolve ambiguity. But language designers are aesthetically motivated, and having only one of a matched pair of characters would look just awful. There are languages which delimit the end but not the start of a condition, e.g. Bash, but no one has ever accused them of looking good.


问:
Why is the factory method design pattern more useful than having classes and calling them individually?
From the "Gang of Four" design patterns, there's the Factory method:

```<code>class Factory(product)
  case product
  when a
    new A
  when b
    new B
  when c
    new C
end

new Factory(a)
</code>```

Why is this more useful than having three classes, a, b, and c and calling them individually?

答:
The Factory pattern is the most overused and abused design pattern.

I have come across numerous cases where a Factory class is coded when a simple constructor would be adequate.

Dont use a factory class unless:-

You depend on an external resource but you don't know exactly which one yet.

Construction is expensive and you want to build once and reuse many times.

Constructing a new instance depends on what instances have already been constructed (e.g. Your can only have five connections, or, you should use a connection id number one more than the last number used).


答:
Scala is designed not only to be interoperable with its host platform technically, but also socially, i.e. it is designed to be familiar to existing programmers of the host platform. And on almost all the host platforms that the Scala community could potentially be interested in (JVM, CLI, ECMAScript, Objective-C/Core Foundation/Cocoa, Unix, Windows), the dominant language(s) (Java, C#, ECMAScript, Objective-C, C, C++) use this syntax. That's why Martin Odersky chose it: familiarity.

However, when Martin Odersky was asked what the one thing was that he introduced for compatibility with Java and that he would like to change, he mentioned exactly this syntax.

This asymmetry of having an if keyword to indicate the condition, an else keyword to indicate the else branch, but no corresponding then keyword to indicate the then branch needlessly complicates the syntax, and he wishes that he had chosen to use a then keyword instead. Unfortunately, it is impossible to introduce this in a backwards-compatible manner, so it will likely stay the way it is forever.

Title: Why does scala require parenthesis around the condition of an if statement

Body: Just curious, from a syntax parsing perspective, why does Scala actually require parentheses around the condition of an if statement, given that the only thing allowed after if is (?


答:
If you always want to avoid playing a new entity in a location that has already been allocated to something else, you can change around your process slightly. This would guarantee unique locations, but it requires a bit more overhead. Here are the steps:

Setup a collection of references to all possible locations on the map (for the 20x20 map, this would be 400 locations)

Pick a location at random from this collection of 400 (rand() would work fine for this)

Remove this possibility from the possible locations collection (so it now has 399 possibilities)

Repeat until all entities have a specified location

So long as you're removing the location from the set you are picking from, there should be no chance of a second entity receiving the same location (unless you're picking the locations from more than one thread at once).

A real world analogue to this would be drawing a card from a deck of cards. Currently, you're shuffling the deck, drawing a card and marking it down, putting the drawn card back into the deck, re-shuffling and drawing again.  The above approach skips putting the card back into the deck.


答:
Blame the designers of B!

The choice to use a pair of parentheses to delimit conditions is not specific to Scala, but is common to all languages based on C-syntax, including Java, C++, C# and even JavaScript. Those languages are based on C-syntax simply because it is familiar to many developers. And C inherited this syntax from its predecessor B (which like C was designed by Ken Thompson).

A language like Lisp does not require delimiters around conditions:

```<code>(if x do-something do-something-else)
</code>```

But this is only possible because of the regularity of the Lisp-syntax. In a language with in infix-operators, this will lead to ambiguities, because

```<code>if a ++ b;
</code>```

could mean either

```<code>if (a) ++b;
</code>```

or

```<code>if (a++) b;
</code>```

So, while the opening parenthesis after if is theoretically not necessary, you do need some token to separate the end of the condition from the following statement.

Python for example uses a colon for this purpose:

```<code>if a == b:
   do_something()
</code>```

A lot of languages, like Pascal, Basic, OCaml, F#, Haskell uses the keyword then:

```<code>if a == b then do_something
</code>```

So the question comes down to why the designers of B decided to use a set of parenthesis to delimit conditions? BCPL, the predecessor to B, uses the keyword 'do', so it was an active choice by the designers of B to use parenthesis instead.

I can't answer that (only the designers of B can), but a reasonable assumption is they preferred to use special characters rather than keywords (perhaps to make it quicker to type and keep the number of reserved keywords low), and since parentheses are already used to delimit sub-expressions, it seem like a logical choice.

Body:
Blame the designers of B!

The choice to use a pair of parentheses to delimit conditions is not specific to Scala, but is common to all languages based on C-syntax, including Java, C++, C# and even JavaScript. Those languages are based on C-syntax simply because it is familiar to many developers. And C inherited this syntax from its predecessor B (which like C was designed by Ken Thompson).

A language like Lisp does not require delimiters around conditions:

(if x do-something do-something-else)

But this is only possible because of the regularity of the Lisp-syntax. In a language with in infix-operators, this will lead to ambiguities, because

if a ++ b;

could mean either

if (a) ++b;

or

if (a++) b;

So, while the opening parenthesis after if is theoretically not necessary, you do need some token to separate the end of the condition from the following statement.

Python for example uses a colon for this purpose:

if a == b:
   do_something()

A lot of languages, like Pascal, Basic, OCaml, F#, Haskell uses the keyword then:

if a == b then do_something

So the question comes down to why the designers of B decided to use a set of parenthesis to delimit conditions? BCPL, the predecessor to B, uses the keyword 'do', so it was an active choice by the designers of B to use parenthesis instead.

I can't answer that (only the designers of B can), but a reasonable assumption is they preferred to use special characters rather than keywords (perhaps to make it quicker to type and keep the number of reserved keywords low), and since parentheses are already used to delimit sub-expressions, it seem like a logical choice.


问:
Unknown design pattern
I am currently trying to refactor some code and one of the problems I came across was the constructors had far too many parameters (15 in fact) and was being initialised by another object which had the same amount of properties.

I am meant to be reducing the amount of classes we have so creating a set of classes which represented the different parts of the parameters seemed silly so I began looking and the best answer I came across was from  this question on stackoverflow.

```<code>public class DoSomeActionParameters
{
    readonly string _a;
    readonly int _b;

    public string A { get { return _a; } }
    public int B{ get { return _b; } }

    DoSomeActionParameters(Initializer data)
    {
        _a = data.A;
        _b = data.B;
    }

    public class Initializer
    {
        public Initializer()
        {
            A = "(unknown)";
            B = 88;
        }

        public string A { get; set; }
        public int B { get; set; }
    }

    public static DoSomeActionParameters Create(Action<Initializer> assign)
    {
        var i = new Initializer();
        assign(i)

        return new DoSomeActionParameters(i);
    }
}
</code>```

which can be called like so using a lambda

```<code>DoSomeAction(
    DoSomeActionParameters.Create(
        i => {
            i.A = "Hello";
        })
    );
</code>```

I really liked this method even though it doesn't solve directly the problem of actually initialising the class, it does make it mean that I can have one constructor instead of 3. Also it doesn't require my class to know about objects it doesn't care about.

My problem is however, I do not know what this pattern is called so I can't do any further research on it to find out if it is still valid, is superseded by
another pattern or whether it has sever performance issues. From my research the closest pattern I could find is the builder pattern but it seems to be more of an extension on that.

As a bonus point, it would be great if you could give me a hand with how to make certain parameters mandatory as we have about 10 parameters from the database and 5 more which are just flags which we don't really need to know about.

答:
I'd call this the "Elephant in the Room" (anti)pattern. You are focusing on the minutiae whilst ignoring the bigger problem. If you have a class that requires 15 constructor parameters, then this a warning sign that the class is doing too much and thus needs too much configuration.

The "pattern" you need here therefore is the Single Responsibility Principle. Examine the class, work out how many (likely quite distinct) things it's doing and start breaking those out into smaller, more focused, classes. Each will only then need a few constructor parameters.

To begin with, this will create more classes; but they'll be good classes. As you apply this to the mutated mess of similar classes, you'll be able to replace large parts of those with your new classes and what's  left will again be better quality, more focused classes.

Title: Unknown design pattern


问:
Send signal to a scala process
I have a cron job running that is a Scala application. I want another job, that runs forever, to do something when this one finishes. It seems to me some kind of signal (Unix/Linux signal?) has to be sent for this.

For e.g., the first job writes to a file and after it finishes the second job (which is already running) reads from that file and does something.

How should I proceed with this?

答:
I think the safest way to do this is for the long-running process to listen to a socket. Once the short process is done, it connects to that socket, sends over any relevant information, and disconnects.

Socket communication to localhost should never fail, so this should not introduce any meaningful risk. Sockets are better than using files to synchronize because there is no risk another process or user will alter or delete the file, and file permissions cannot prevent a socket from working.

As with other methods, sockets allow you to send arbitrary information. It could be as simple as "hi, go do your thing" or it could be a complex serialized data structure. Whatever you need.

Finally, sockets typically work by using streams to serialize and deserialize data on both ends. Both sockets and streams are very standard and established communication methods supported by virtually all operating systems and programming environments. Even if you change your technology stack in the future or expand to work with a program written in a different language in addition to what you have today, that part should still work.

I recommend checking out the list of registered IP ports and picking one that is not in use. According to the bottom of the page, ports in the range 49,152 to 65,535 cannot be registered and should be available for any use (including this one) without interfering with standard applications (e.g. an FTP/SFTP server).

Title: Send signal to a scala process


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
A working brain is what you need the most.

Everything else depends upon it


答: Have a look at the Builder Pattern.  It solves exactly the problem you are having - too many parameters in a constructor.  You wind up with an empty constructor (typically in Java this will be a private method, if you use an inner class as the Builder) and setter methods (which may also remain private), then a Builder class with chained methods which call the setters, and a build() method which constructs the object and populates its fields.</p>

Title: Unknown design pattern

Body:
I am currently trying to refactor some code and one of the problems I came across was the constructors had far too many parameters (15 in fact) and was being initialised by another object which had the same amount of properties.

I am meant to be reducing the amount of classes we have so creating a set of classes which represented the different parts of the parameters seemed silly so I began looking and the best answer I came across was from  this question on stackoverflow.

```<code>public class DoSomeActionParameters
{
    readonly string _a;
    readonly int _b;

    public string A { get { return _a; } }
    public int B{ get { return _b; } }

    DoSomeActionParameters(Initializer data)
    {
        _a = data.A;
        _b = data.B;
    }

    public class Initializer
    {
        public Initializer()
        {
            A = "(unknown)";
            B = 88;
        }

        public string A { get; set; }
        public int B { get; set; }
    }

    public static DoSomeActionParameters Create(Action<Initializer> assign)
    {
        var i = new Initializer();
        assign(i)

        return new DoSomeActionParameters(i);
    }
}
</code>```

which can be called like so using a lambda

```<code>DoSomeAction(
    DoSomeActionParameters.Create(
        i => {
            i.A = "Hello";
        })
    );
</code>```

I really liked this method even though it doesn't solve directly the problem of actually initialising the class, it does make it mean that I can have one constructor instead of 3. Also it doesn't require my class to know about objects it doesn't care about.

My problem is however, I do not know what this pattern is called so I can't do any further research on it to find out if it is still valid, is superseded by
another pattern or whether it has sever performance issues. From my research the closest pattern I could find is the builder pattern but it seems to be more of an extension on that.

As a bonus point, it would be great if you could give me a hand with how to make certain parameters mandatory as we have about 10 parameters from the database and 5 more which are just flags which we don't really need to know about.


问:
Is this data model a list or tree?
Using python syntax with below environment diagram, teacher taught us that there are 11 trees(orange boundary) in this diagram, including leaf.

It has been taught here,

lists are represented as a row of index-labeled adjacent boxes, one per element. Each box either contains a primitive value or points to a compound value. For example:

```<code>nested_list = [   [1, 2],    [],     [[3, False, None],[4, lambda : 5]]   ]
</code>```

tree is either a single value called a leaf or a sequence of trees. Typically some type restriction is placed on the leaves. E.g a tree of numbers. For example:

```<code>tree = [     [1, [2], 3, []],      [[4], [5,6]],       7    ]
</code>```

My question:

In general, Can a tree have heterogeneous type data? for example: Can I say, abc = [1, 2, 3, 4, lamda: 5] a tree with 5 leaves?

Note: Intention is to understand, whether tree can have heterogeneous type data

答:
I think you are confusing the issue by using lambda expressions in the structure. The expression lambda:5 is neither a list nor a number. It is a function. So the data structure in your example is not a tree of numbers, since one of the leaves is a function rather than a number.

But disregarding the lambda, the expression [1, 2, 3, 4] is a list, and also a tree according the definition of tree you provide (because it is a sequence of trees, where each tree is a leaf). This is not a contradiction, since according to the definition you provide, any list will also be a tree.

Title: Is this data model a list or tree?


问:
Multi-pattern matching
I have a given byte array in C and I need to match it against several byte arrays and return true if there is any match.

I can make various memcmp's but I feel that it is very inefficient.

Do you know a better way?

答:
In principle a search Trie is what you want, but you'd have to profile your actual data to find out when that actually performs better (it might always be worse unless you can find a cache-friendly layout).

Edit based on comments:

Are you matching a stream or discrete packets?

If the former, and you need to handle matches spanning the boundary between consecutive byte-arrays, you definitely want ratchet freak's DFA.

If the latter, your tradeoff depends on:

Hardware characteristics

The cache effects I originally mentioned are very platform dependent.

If you have a reasonably-sized fast cache (ie your substrings fit in it), then direct memcmp may be faster. Profile. You can speed this up by sorting your substrings and using the return value of memcmp to perform binary search on them.

Especially for an embedded system, if the cache is small or the penalty for missing not that large, or your substrings don't fit in cache anyway, then chasing Trie nodes around is fine

tl;dr - Trie is asymptotically optimal but cache effects may dominate. Measure it!

Title: Multi-pattern matching


答:
prefix trie:

It's a degenerate DFA without cycles. For implementation you have a int state and a int nextState[256] for each state.

For Matching states you would make the state number for it negative so you know when it's reached.

Title: Multi-pattern matching

Body:
I have a given byte array in C and I need to match it against several byte arrays and return true if there is any match.

I can make various memcmp's but I feel that it is very inefficient.

Do you know a better way?


问:
Database Design: Rules for students and student groups
I am new to databases. I am using MySql.

What I have is a student system which stores rules for students in a school.

Each student may or may not be a part of a group (Soccer, Guitar, etc).

Different rules are imposed on individual students and also on groups.

Student table:

```<code>|Student_id|Student_name|
|----------|------------|
|         1|Jack        |
|         2|John        |
|         3|Bob         |
|----------|------------|
</code>```

Group table:

```<code>|Group_id|Group_name|
|--------|----------|
|       1|Soccer    |
|--------|----------|
</code>```

Student_group_table:

```<code>|Student_id|Group_id|
|----------|--------|
|         1|       1|   --Jack plays soccer
|         2|       1|   --John also plays soccer
|----------|--------|
</code>```

Rules (dirty design):

```<code>|id|entity_id|entity_type|rule      |
|--|---------|-----------|----------|
| 1|        3|student    |Bus at 7am| --Bob has to catch bus at 7am
| 2|        1|group      |Shoes     | --All soccer students must bring shoes
|--|---------|-----------|----------|
</code>```

I would appreciate a cleaner alternative to this dirty design.

答:
An alternative to @Thomas comment (which is viable, although imo recursive foreign keys add too much complexity if you do not need the additional power they give) would be to create separate tables for each foreign-key type (one for students, one for groups), allowing for enforceable foreign keys:

Rules:

```<code>|id|rule      |
|--|----------|
| 1|Bus at 7am| -- bus has to be caught at 7am
| 2|Shoes     | -- shoes have to be brought
|--|----------|
</code>```

student_rules_table:

```<code>|Student_id|rule_id |
|----------|--------|
|         3|       1| --Bob has to follow rule 1
|----------|--------|
</code>```

group_rules_table:

```<code>|Group_id  |rule_id |
|----------|--------|
|         1|       2| --All soccer students have to follow rule 2
|----------|--------|
</code>```

This would also result in a lower number of distinct rules, since these are no longer dependent on any connected entity.

Body:
An alternative to @Thomas comment (which is viable, although imo recursive foreign keys add too much complexity if you do not need the additional power they give) would be to create separate tables for each foreign-key type (one for students, one for groups), allowing for enforceable foreign keys:

Rules:

|id|rule      |
|--|----------|
| 1|Bus at 7am| -- bus has to be caught at 7am
| 2|Shoes     | -- shoes have to be brought
|--|----------|

student_rules_table:

|Student_id|rule_id |
|----------|--------|
|         3|       1| --Bob has to follow rule 1
|----------|--------|

group_rules_table:

|Group_id  |rule_id |
|----------|--------|
|         1|       2| --All soccer students have to follow rule 2
|----------|--------|

This would also result in a lower number of distinct rules, since these are no longer dependent on any connected entity.


问:
Should I initialize C structs via parameter, or by return value?
The company I work at is initializing all of their data structures through an initialize function like so:

```<code>//the structure
typedef struct{
  int a,b,c;
} Foo;

//the initialize function
InitializeFoo(Foo* const foo){
   foo->a = x; //derived here based on other data
   foo->b = y; //derived here based on other data
   foo->c = z; //derived here based on other data
}

//initializing the structure
Foo foo;
InitializeFoo(&foo);
</code>```

I've gotten some push back trying to initialize my structs like this:

```<code>//the structure
typedef struct{
  int a,b,c;
} Foo;

//the initialize function
Foo ConstructFoo(int a, int b, int c){
   Foo foo;
   foo.a = a; //part of parameter input (inputs derived outside of function)
   foo.b = b; //part of parameter input (inputs derived outside of function)
   foo.c = c; //part of parameter input (inputs derived outside of function)
   return foo;
}

//initialize (or construct) the structure
Foo foo = ConstructFoo(x,y,z);
</code>```

Is there an advantage to one over the other?

Which one should I do, and how would I justify it as a better practice?

答:
In the 2nd approach you will never have a half-initialised Foo. Putting all the construction in one place seems a more sensible, and obvious place.

But... the 1st way isn't so bad, and is often used in many areas (there's even a discussion of the best way to dependency-inject, either property-injection like your 1st way, or constructor injection like the 2nd). Neither is wrong.

So if neither is wrong and the rest of the company uses approach #1, then you should be fitting in with the existing codebase and not trying to mess it up by introducing a new pattern. This is really the most important factor at play here, play nice with your new friends and don't try to be that special snowflake who does things differently.


问:
When should I use a generator and when a list in Python?
I often find it cleaner to write a generator than to return a list. For example, I prefer

```<code>def my_func_gen(foo):
    for i in foo:
        # Do some stuff that's too complicated for a list or generator comprehension
        yield whatever
</code>```

to

```<code>def my_func_list(foo):
    result = []
    for i in foo:
        # Do some stuff that's too complicated for a list or generator comprehension
        result.append(whatever)
    return result
</code>```

Further, this answer says, "You're encouraged to use iterators for everything." So is my_func_gen better, then? Maybe not. I'd like for the caller not to even know whether it's getting a list or an iterator. But the caller has to think about it because, for example, the iterator won't be sliceable using Python's nice clean syntax; I'll have to use itertools.islice.

So what should I do?

Ignore the advice to "use iterators for everything"

Get out of the habit of using slices and other behavior that's not available to all iterables

Run list(my_iterable) any time I might want to use features that lists support and generators do not

Use lists sometimes and generators others. But when?

Related: here's some code that users a wrapper class to make any iterator sliceable. It doesn't work quite the way you might think, though: looking up foo[:2] and then looking up foo[:2] again gives different results.

答:
You are confused between generators and iterators. They are not the same concept at all.

Iterators are great and ubiquitous in Python. You should use them a lot. Both my_func_gen and
my_func_list use them.

Generators are a lazy way to build iterables. They are useful when the fully realized list would not
fit in memory, or when the cost to calculate each list element is high and you want to do it as late
as possible. But they can only be iterated over once.

I invite you to go through this.


问:
Instantiating class that contains methods to check some of the settings and also return values from my app.config file
I am writing a console application and  have a class called ApplicationConfiguration that contains methods to check some of the settings and also return values from my app.config file.  For instance the following method in the ApplicationConfiguration class returns the location of log file from my app.config file:

```<code>public string ProjectLog
        {
            get
            {
                _projectLog = ConfigurationManager.AppSettings["ProjectLog"].ToString();
                return _projectLog;
            }
        }
</code>```

I have a FileLogger class and DBConnection class that also would need values returned from methods in ApplicationConfiguration.    My question is since the values in the app.config file are used in many of my other classes do I have to instantiate ApplicationConfiguration in every class that may need my config values like so?

```<code>public class FileLogger
  {
        ApplicationConfiguration appConfig = new ApplicationConfiguration();
   }
public class DBConnection
  {
        ApplicationConfiguration appConfig = new ApplicationConfiguration();
  }
</code>```

答:
If you are sure that your configuration setting stuff is not likely to change much, then you can wrap your configuration class in the sometimes-maligned "static" modifier like so:

```<code>namespace ConsoleAppName
{
    class Program
    {
        static void Main(string[] args)
        {
            var _projectLog = MyAppConfiguration.LogLocation;
        }
    }

    public static class MyAppConfiguration
    {
        public static string LogLocation
        {
            get { return ConfigurationManager.AppSettings["ProjectLog"]; }
        }
    }
}
</code>```

Doing it this way "locks" you into having just one way of returning these settings, but if you are reasonibly sure you won't need to conditionally load different settings from the console's config based on runtime conditions, then its perfectly reasonable and clear to do it this way. Regardless, this method will give you the room to do things later like pull that setting from a database and cache it, if such a requirement arises.

Body:
If you are sure that your configuration setting stuff is not likely to change much, then you can wrap your configuration class in the sometimes-maligned "static" modifier like so:

namespace ConsoleAppName
{
    class Program
    {
        static void Main(string[] args)
        {
            var _projectLog = MyAppConfiguration.LogLocation;
        }
    }

    public static class MyAppConfiguration
    {
        public static string LogLocation
        {
            get { return ConfigurationManager.AppSettings["ProjectLog"]; }
        }
    }
}

Doing it this way "locks" you into having just one way of returning these settings, but if you are reasonibly sure you won't need to conditionally load different settings from the console's config based on runtime conditions, then its perfectly reasonable and clear to do it this way. Regardless, this method will give you the room to do things later like pull that setting from a database and cache it, if such a requirement arises.


答:
This seems like a good use case for the singleton pattern.

Basically, it allows you to have a single class that is created once throughout the lifetime of the system, that gets created when it is accessed.

Here's a simple example:

```<code>public sealed class Configuration
{
    private static Configuration instance = null;
    private static readonly object padlock = new object();

    private string _logLocation;
    public string LogLocation { get { return _logLocation; } }

    Configuration()
    {
        _logLocation = ConfigurationManager.AppSettings["ProjectLog"];
    }

    public static Configuration Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}
</code>```

Then call it anywhere like this:

```<code>Configuration.Instance.LogLocation
</code>```

While I generally agree with the general consensus that singletons are an antipattern, I've used a slightly modified version of this pattern to great success with some configuration type data.

As always, YMMV.

Title: Instantiating class that contains methods to check some of the settings and also return values from my app.config file

Body:
I am writing a console application and  have a class called ApplicationConfiguration that contains methods to check some of the settings and also return values from my app.config file.  For instance the following method in the ApplicationConfiguration class returns the location of log file from my app.config file:

```<code>public string ProjectLog
        {
            get
            {
                _projectLog = ConfigurationManager.AppSettings["ProjectLog"].ToString();
                return _projectLog;
            }
        }
</code>```

I have a FileLogger class and DBConnection class that also would need values returned from methods in ApplicationConfiguration.    My question is since the values in the app.config file are used in many of my other classes do I have to instantiate ApplicationConfiguration in every class that may need my config values like so?

```<code>public class FileLogger
  {
        ApplicationConfiguration appConfig = new ApplicationConfiguration();
   }
public class DBConnection
  {
        ApplicationConfiguration appConfig = new ApplicationConfiguration();
  }
</code>```

Body:
This seems like a good use case for the singleton pattern.

Basically, it allows you to have a single class that is created once throughout the lifetime of the system, that gets created when it is accessed.

Here's a simple example:

public sealed class Configuration
{
    private static Configuration instance = null;
    private static readonly object padlock = new object();

    private string _logLocation;
    public string LogLocation { get { return _logLocation; } }

    Configuration()
    {
        _logLocation = ConfigurationManager.AppSettings["ProjectLog"];
    }

    public static Configuration Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Then call it anywhere like this:

Configuration.Instance.LogLocation

While I generally agree with the general consensus that singletons are an antipattern, I've used a slightly modified version of this pattern to great success with some configuration type data.

As always, YMMV.


答:
Only your program should know that appsettings exists. read it out and pass it in to your other objects. Easy</p>

```<code>    public class Program
    {
        static void Main(string[] args)
        {
            var projectLog = ConfigurationManager.AppSettings["ProjectLog"];
            FileLogger logger = new FileLogger(projectLog);
            DbConnection dbConn = new DbConnection(projectLog);
            //etc etc
        }
    }

  public class FileLogger
  {
        private string logLocation;
        public FileLogger(string logLocation)
        {
            this.logLocation = loglocation;
        }
   }
</code>```

Body:
Only your program should know that appsettings exists. read it out and pass it in to your other objects. Easy

    public class Program
    {
        static void Main(string[] args)
        {
            var projectLog = ConfigurationManager.AppSettings["ProjectLog"];
            FileLogger logger = new FileLogger(projectLog);
            DbConnection dbConn = new DbConnection(projectLog);
            //etc etc
        }
    }

  public class FileLogger
  {
        private string logLocation;
        public FileLogger(string logLocation)
        {
            this.logLocation = loglocation;
        }
   }