问:
How to enforce good/better source code control practices?
I suspect that I'm focusing on the wrong problem so I will first describe what I think the problem is before presenting the possibly suboptimal solution I envision.

Current Situation:

Currently my co-workers commit their code changes only after loooong periods of time in huge chunks with changes spreading all over the project(s). That's progress I guess, because not long ago they just put .zip archives on some network share. Still, merging is a nightmare - and frankly I've had enough of it. And I'm also tired of talking and explaining and begging. This just has to stop - without me constantly being "the bad guy".

My solution:

Since there seems to be no awareness of and/or no interest in the problems and I cannot expect any efforts to last longer than a few days ...strike that, hours, I'd like the subversion server to do the nagging.

My question:

Am I way off-base here or am I looking at the wrong problem?  It seems like I'm missing something, and I think I'm asking the wrong thing by looking at tools to solve my problem.

Should I be looking for a tool to solve this problem or what is it I should do to fix this?

答:
An organization I contracted for in the past wanted to solve this same problem, and came up with a fairly good social solution: developers do not have their own computers.  The development TEAM has computers, but any individual can be asked and expected to work on any development computer on any given day.  So, checking in is the only way to make sure you can continue working on what you were doing yesterday!

Management then went around and surreptitiously reverted changes on computers after hours so that anything not checked in was lost.  These "simulated computer failures" only had to occur a few times before the devs got on board.

Of course, it's important to explain the "why" of rules as well as the "what".  Unless the "why" is made clear, they could just store their source on USB drives or something.


问:
Should a front-end developer ever specify JSON format for back-end developers?
I am taking the front-end role in a project. Should I be specifying for my back-end teammates the exact format of JSON that their PHP returns to my JavaScript?

For example, should I be telling them they should use a format similar to one described here:

Proper way to structure JSON for front-end consumption

Or should I keep my role as sterile as possible, and simply describe in words the inputs and outputs I need from their back-end interface? (Of course, if this happens it might be more difficult on my part to handle their different data structure formats)

答:
You most definetly should contribute to how the format and structure of the JSON should look like. I see it more than often that the front-end engineers, the API consumers, is the ones knowing how the data-structure should be.

You are the one going to use the data, format it, loop through it and work with it. You should have an opinion on how you want it delivered.

ContentLicense: CC BY-SA 3.0


问:
Concept for dealing with recurring appointments
Our company implemented a calendar system a few months back with recurring appointments,  using iCal strings to store the recurring appointment criteria.

We are starting to run into performance problems because of these.

Our current thinking is something along these lines...

A user requests all appointments for a date range.  Typically no more than 30 days.

We grab all non-recurring events from the database that fall in this date range.
Then we grab ALL events that contain an iCal string and run each one through a processor to determine if the event happens to repeat in our requested date range.  For example, the user may have the event starting on 1/1/14, repeating every Tuesday and Wednesday ongoing forever.  Another event, however, may begin on 1/1/14, repeating every Tuesday and Wednesday for one month and is now outside of our selected range.  The first one would repeat to our date range and be included.  The second one would not.

As far as I can tell, there really isn't any good way to determine any kind of filtering so that I don't have to pull every single one of these events from the database and test them to see if they match our date range.

As the number of recurring events grows, our database is being slogged down with requests that return more and more records, and our server needs to process each of these, most of which aren't necessary, but we don't know until we get them to the server and process them.

Has anybody faced this before, and is there a better algorithm that we can implement to limit the number of records returned?

答:
I would like to offer you my solution for this by recognizing that:

All appointments, single or re-occurring, have at least a date

Under reasonable settings, re-occurring appointments often have a pattern

In my solution, you will have for each appointment a start date and an end date. In the case of single appointment, you can leave the end date the same as the start date. In the case of re-occurring appointment into the future, you can leave the end date as empty or any far into the future value.

Now for all appointments, you have an addition column called: type and pattern.
In this column, you can have an enum kind of values specifying the repetition pattern such as daily, weekly, monthly, bi-weekly. For appointments that are not re-occurring, the type can be one-time.

This also deals with the case where an appointment is actually part of a re-occurring one, but was re-scheduled to be out of pattern. You set the type of it into something such as re-schedule can possibly have an additional reference column to refer to the original re-occurring appointment.

Now when you want to search for all appointments (of any types) to match your date range, you can use the start and end date together with the 'type and pattern' column.
A specific example for the case of search for appointments in the range of Oct 1st, 2014 to Dec 1st, 2014 is as follows:

select * from APP as A where
    ((A.sd >= $start AND A.sd <= $end) OR (A.ed <= $end AND A.ed >= $start) OR (A.sd <= $start AND A.ed >= $end) )
    AND (A.type = 'Single' OR A.type = 'ReSchedule' OR inRange($start, $end, A.sd, A.type) )
```

Here you have to build your own function for inRange(), the semantic is taking the $end variable as an integer, minus the integer for A.sd and divide by the pattern interval. Then you check if $end minus the division's mod is greater or equal to $start

InRange() will slow down your query by looking at all raw matches. But this will be much better than your original design concept. You can either implement InRange() by using PL/SQL or write an external method using the SQL query's results to properly filter the raw matches.

Body:
I would like to offer you my solution for this by recognizing that:

All appointments, single or re-occurring, have at least a date

Under reasonable settings, re-occurring appointments often have a pattern

In my solution, you will have for each appointment a start date and an end date. In the case of single appointment, you can leave the end date the same as the start date. In the case of re-occurring appointment into the future, you can leave the end date as empty or any far into the future value.

Now for all appointments, you have an addition column called: type and pattern.
In this column, you can have an enum kind of values specifying the repetition pattern such as daily, weekly, monthly, bi-weekly. For appointments that are not re-occurring, the type can be one-time.

This also deals with the case where an appointment is actually part of a re-occurring one, but was re-scheduled to be out of pattern. You set the type of it into something such as re-schedule can possibly have an additional reference column to refer to the original re-occurring appointment.

Now when you want to search for all appointments (of any types) to match your date range, you can use the start and end date together with the 'type and pattern' column.
A specific example for the case of search for appointments in the range of Oct 1st, 2014 to Dec 1st, 2014 is as follows:

select * from APP as A where
    ((A.sd >= $start AND A.sd <= $end) OR (A.ed <= $end AND A.ed >= $start) OR (A.sd <= $start AND A.ed >= $end) )
    AND (A.type = 'Single' OR A.type = 'ReSchedule' OR inRange($start, $end, A.sd, A.type) )

Here you have to build your own function for inRange(), the semantic is taking the $end variable as an integer, minus the integer for A.sd and divide by the pattern interval. Then you check if $end minus the division's mod is greater or equal to $start

InRange() will slow down your query by looking at all raw matches. But this will be much better than your original design concept. You can either implement InRange() by using PL/SQL or write an external method using the SQL query's results to properly filter the raw matches.


问:
How to define "or" logically
Recently, I came across a problem that required me to define the logical "OR" operator programmatically, but without using the operator itself.

What I came up with is this:

OR(arg1, arg2)
  if arg1 = True and arg2 = True
     return True

  else if arg1 = True and arg2 = False
     return True

  else if arg1 = False and arg2 = True
     return True

  else:
     return False
```

Is this logic correct, or did I miss something?

答:
Functions (ECMAScript)

All you need are function definitions and function calls. You don't need any branching, conditionals, operators or builtin functions. I will demonstrate an implementation using ECMAScript.

First, let's define two functions called true and false. We could define them any way we want, they are completely arbitrary, but we will define them in a very special way which has some advantages as we will see later:

const tru = (thn, _  ) => thn,
      fls = (_  , els) => els;
```

<p><code>tru</code> is a function with two parameters which simply ignores its second argument and returns the first. <code>fls</code> is also a function with two parameters which simply ignores its first argument and returns the second.</p>

<p>Why did we encode <code>tru</code> and <code>fls</code> this way? Well, this way, the two functions not only represent the two concepts of <code>true</code> and <code>false</code>, no, at the same time, they also represent the concept of "choice", in other words, they are also an <code>if</code>/<code>then</code>/<code>else</code> expression! We evaluate the <code>if</code> condition and pass it the <code>then</code> block and the <code>else</code> block as arguments. If the condition evaluates to <code>tru</code>, it will return the <code>then</code> block, if it evaluates to <code>fls</code>, it will return the <code>else</code> block. Here's an example:</p>

<pre class="lang-js prettyprint-override"><code>tru(23, 42);
// => 23
</code>```

This returns 23, and this:

fls(23, 42);
// => 42
```

<p>returns <code>42</code>, just as you would expect.</p>

<p>There is a wrinkle, however:</p>

<pre class="lang-js prettyprint-override"><code>tru(console.log("then branch"), console.log("else branch"));
// then branch
// else branch
</code>```

This prints both then branch and else branch! Why?

Well, it returns the return value of the first argument, but it evaluates both arguments, since ECMAScript is strict and always evaluates all arguments to a function before calling the function. IOW: it evaluates the first argument which is console.log("then branch"), which simply returns undefined and has the side-effect of printing then branch to the console, and it evaluates the second argument, which also returns undefined and prints to the console as a side-effect. Then, it returns the first undefined.

In λ-calculus, where this encoding was invented, that's not a problem: λ-calculus is pure, which means it doesn't have any side-effects; therefore you would never notice that the second argument also gets evaluated. Plus, λ-calculus is lazy (or at least, it is often evaluated under normal order), meaning, it doesn't actually evaluate arguments which aren't needed. So, IOW: in λ-calculus the second argument would never be evaluated, and if it were, we wouldn't notice.

ECMAScript, however, is strict, i.e. it always evaluates all arguments. Well, actually, not always: the if/then/else, for example, only evaluates the then branch if the condition is true and only evaluates the else branch if the condition is false. And we want to replicate this behavior with our iff. Thankfully, even though ECMAScript isn't lazy, it has a way to delay the evaluation of a piece of code, the same way almost every other language does: wrap it in a function, and if you never call that function, the code will never get executed.

So, we wrap both blocks in a function, and at the end call the function that is returned:

tru(() => console.log("then branch"), () => console.log("else branch"))();
// then branch
```

<p>prints <code>then branch</code> and </p>

<pre class="lang-js prettyprint-override"><code>fls(() => console.log("then branch"), () => console.log("else branch"))();
// else branch
</code>```

prints else branch.

We could implement the traditional if/then/else this way:

const iff = (cnd, thn, els) => cnd(thn, els);

iff(tru, 23, 42);
// => 23

iff(fls, 23, 42);
// => 42
```

<p>Again, we need some extra function wrapping when calling the <code>iff</code> function and the extra function call parentheses in the definition of <code>iff</code>, for the same reason as above:</p>

<pre class="lang-js prettyprint-override"><code>const iff = (cnd, thn, els) => cnd(thn, els)();

iff(tru, () => console.log("then branch"), () => console.log("else branch"));
// then branch

iff(fls, () => console.log("then branch"), () => console.log("else branch"));
// else branch
</code>```

Now that we have those two definitions, we can implement or. First, we look at the truth table for or: if the first operand is truthy, then the result of the expression is the same as the first operand. Otherwise, the result of the expression is the result of the second operand. In short: if the first operand is true, we return the first operand, otherwise we return the second operand:

const orr = (a, b) => iff(a, () => a, () => b);
```

<p>Let's check out that it works:</p>

<pre class="lang-js prettyprint-override"><code>orr(tru,tru);
// => tru(thn, _) {}

orr(tru,fls);
// => tru(thn, _) {}

orr(fls,tru);
// => tru(thn, _) {}

orr(fls,fls);
// => fls(_, els) {}
</code>```

Great! However, that definition looks a little ugly. Remember, tru and fls already act like a conditional all by themselves, so really there is no need for iff, and thus all of that function wrapping at all:

```<code>const orr = (a, b) => a(a, b);
</code>```

There you have it: or (plus other boolean operators) defined with nothing but function definitions and function calls in just a handful of lines:

const tru = (thn, _  ) => thn,
      fls = (_  , els) => els,
      orr = (a  , b  ) => a(a, b),
      nnd = (a  , b  ) => a(b, a),
      ntt = a          => a(fls, tru),
      xor = (a  , b  ) => a(ntt(b), b),
      iff = (cnd, thn, els) => cnd(thn, els)();
```

<p>Unfortunately, this implementation is rather useless: there are no functions or operators in ECMAScript which return <code>tru</code> or <code>fls</code>, they all return <code>true</code> or <code>false</code>, so we can't use them with our functions. But there's still a lot we can do. For example, this is an implementation of a singly-linked list:</p>

<pre class="lang-js prettyprint-override"><code>const cons = (hd, tl) => which => which(hd, tl),
      car  = l => l(tru),
      cdr  = l => l(fls);
</code>```

Objects (Scala)

You may have noticed something peculiar: tru and fls play a double role, they act both as the data values true and false, but at the same time, they also act as a conditional expression. They are data and behavior, bundled up into one … uhm … "thing" … or (dare I say) object!

Indeed, tru and fls are objects. And, if you have ever used Smalltalk, Self, Newspeak or other object-oriented languages, you will have noticed that they implement booleans in exactly the same way. I will demonstrate such an implementation here in Scala:

sealed abstract trait Buul {
  def apply[T, U <: T, V <: T](thn: ⇒ U)(els: ⇒ V): T
  def &&&(other: ⇒ Buul): Buul
  def |||(other: ⇒ Buul): Buul
  def ntt: Buul
}

case object Tru extends Buul {
  override def apply[T, U <: T, V <: T](thn: ⇒ U)(els: ⇒ V): U = thn
  override def &&&(other: ⇒ Buul) = other
  override def |||(other: ⇒ Buul): this.type = this
  override def ntt = Fls
}

case object Fls extends Buul {
  override def apply[T, U <: T, V <: T](thn: ⇒ U)(els: ⇒ V): V = els
  override def &&&(other: ⇒ Buul): this.type = this
  override def |||(other: ⇒ Buul) = other
  override def ntt = Tru
}

object BuulExtension {
  import scala.language.implicitConversions
  implicit def boolean2Buul(b: ⇒ Boolean) = if (b) Tru else Fls
}

import BuulExtension._

(2 < 3) { println("2 is less than 3") } { println("2 is greater than 3") }
// 2 is less than 3
```

<p>This BTW is why the Replace Conditional With Polymorphism Refactoring always works: you can always replace any and every conditional in your program with polymorphic message dispatch, because as we have just shown, polymorphic message dispatch can replace conditionals by simply implementing them. Languages like Smalltalk, Self and Newspeak are existence proof of that, because those languages don't even have conditionals. (They also don't have loops, BTW, or really <em>any</em> sort of language built-in control structures except for polymorphic message dispatch aka virtual method calls.)</p>

<hr>

<h1>Pattern Matching (Haskell)</h1>

<p>You could also define <code>or</code> using pattern matching, or something like Haskell's partial function definitions:</p>

<pre class="lang-haskell prettyprint-override"><code>True ||| _ = True
_    ||| b = b
</code>```

Of course, pattern matching is a form of conditional execution, but then again, so is object-oriented message dispatch.

Title: How to define "or" logically

Body:
Functions (ECMAScript)

All you need are function definitions and function calls. You don't need any branching, conditionals, operators or builtin functions. I will demonstrate an implementation using ECMAScript.

First, let's define two functions called true and false. We could define them any way we want, they are completely arbitrary, but we will define them in a very special way which has some advantages as we will see later:

const tru = (thn, _  ) => thn,
      fls = (_  , els) => els;

tru is a function with two parameters which simply ignores its second argument and returns the first. fls is also a function with two parameters which simply ignores its first argument and returns the second.

Why did we encode tru and fls this way? Well, this way, the two functions not only represent the two concepts of true and false, no, at the same time, they also represent the concept of "choice", in other words, they are also an if/then/else expression! We evaluate the if condition and pass it the then block and the else block as arguments. If the condition evaluates to tru, it will return the then block, if it evaluates to fls, it will return the else block. Here's an example:

tru(23, 42);
// => 23

This returns 23, and this:

fls(23, 42);
// => 42

returns 42, just as you would expect.

There is a wrinkle, however:

tru(console.log("then branch"), console.log("else branch"));
// then branch
// else branch

This prints both then branch and else branch! Why?

Well, it returns the return value of the first argument, but it evaluates both arguments, since ECMAScript is strict and always evaluates all arguments to a function before calling the function. IOW: it evaluates the first argument which is console.log("then branch"), which simply returns undefined and has the side-effect of printing then branch to the console, and it evaluates the second argument, which also returns undefined and prints to the console as a side-effect. Then, it returns the first undefined.

In λ-calculus, where this encoding was invented, that's not a problem: λ-calculus is pure, which means it doesn't have any side-effects; therefore you would never notice that the second argument also gets evaluated. Plus, λ-calculus is lazy (or at least, it is often evaluated under normal order), meaning, it doesn't actually evaluate arguments which aren't needed. So, IOW: in λ-calculus the second argument would never be evaluated, and if it were, we wouldn't notice.

ECMAScript, however, is strict, i.e. it always evaluates all arguments. Well, actually, not always: the if/then/else, for example, only evaluates the then branch if the condition is true and only evaluates the else branch if the condition is false. And we want to replicate this behavior with our iff. Thankfully, even though ECMAScript isn't lazy, it has a way to delay the evaluation of a piece of code, the same way almost every other language does: wrap it in a function, and if you never call that function, the code will never get executed.

So, we wrap both blocks in a function, and at the end call the function that is returned:

tru(() => console.log("then branch"), () => console.log("else branch"))();
// then branch

prints then branch and

fls(() => console.log("then branch"), () => console.log("else branch"))();
// else branch

prints else branch.

We could implement the traditional if/then/else this way:

const iff = (cnd, thn, els) => cnd(thn, els);

iff(tru, 23, 42);
// => 23

iff(fls, 23, 42);
// => 42

Again, we need some extra function wrapping when calling the iff function and the extra function call parentheses in the definition of iff, for the same reason as above:

const iff = (cnd, thn, els) => cnd(thn, els)();

iff(tru, () => console.log("then branch"), () => console.log("else branch"));
// then branch

iff(fls, () => console.log("then branch"), () => console.log("else branch"));
// else branch

Now that we have those two definitions, we can implement or. First, we look at the truth table for or: if the first operand is truthy, then the result of the expression is the same as the first operand. Otherwise, the result of the expression is the result of the second operand. In short: if the first operand is true, we return the first operand, otherwise we return the second operand:

const orr = (a, b) => iff(a, () => a, () => b);

Let's check out that it works:

orr(tru,tru);
// => tru(thn, _) {}

orr(tru,fls);
// => tru(thn, _) {}

orr(fls,tru);
// => tru(thn, _) {}

orr(fls,fls);
// => fls(_, els) {}

Great! However, that definition looks a little ugly. Remember, tru and fls already act like a conditional all by themselves, so really there is no need for iff, and thus all of that function wrapping at all:

const orr = (a, b) => a(a, b);

There you have it: or (plus other boolean operators) defined with nothing but function definitions and function calls in just a handful of lines:

const tru = (thn, _  ) => thn,
      fls = (_  , els) => els,
      orr = (a  , b  ) => a(a, b),
      nnd = (a  , b  ) => a(b, a),
      ntt = a          => a(fls, tru),
      xor = (a  , b  ) => a(ntt(b), b),
      iff = (cnd, thn, els) => cnd(thn, els)();

Unfortunately, this implementation is rather useless: there are no functions or operators in ECMAScript which return tru or fls, they all return true or false, so we can't use them with our functions. But there's still a lot we can do. For example, this is an implementation of a singly-linked list:

const cons = (hd, tl) => which => which(hd, tl),
      car  = l => l(tru),
      cdr  = l => l(fls);

Objects (Scala)

You may have noticed something peculiar: tru and fls play a double role, they act both as the data values true and false, but at the same time, they also act as a conditional expression. They are data and behavior, bundled up into one … uhm … "thing" … or (dare I say) object!

Indeed, tru and fls are objects. And, if you have ever used Smalltalk, Self, Newspeak or other object-oriented languages, you will have noticed that they implement booleans in exactly the same way. I will demonstrate such an implementation here in Scala:

sealed abstract trait Buul {
  def apply[T, U <: T, V <: T](thn: ⇒ U)(els: ⇒ V): T
  def &&&(other: ⇒ Buul): Buul
  def |||(other: ⇒ Buul): Buul
  def ntt: Buul
}

case object Tru extends Buul {
  override def apply[T, U <: T, V <: T](thn: ⇒ U)(els: ⇒ V): U = thn
  override def &&&(other: ⇒ Buul) = other
  override def |||(other: ⇒ Buul): this.type = this
  override def ntt = Fls
}

case object Fls extends Buul {
  override def apply[T, U <: T, V <: T](thn: ⇒ U)(els: ⇒ V): V = els
  override def &&&(other: ⇒ Buul): this.type = this
  override def |||(other: ⇒ Buul) = other
  override def ntt = Tru
}

object BuulExtension {
  import scala.language.implicitConversions
  implicit def boolean2Buul(b: ⇒ Boolean) = if (b) Tru else Fls
}

import BuulExtension._

(2 < 3) { println("2 is less than 3") } { println("2 is greater than 3") }
// 2 is less than 3

This BTW is why the Replace Conditional With Polymorphism Refactoring always works: you can always replace any and every conditional in your program with polymorphic message dispatch, because as we have just shown, polymorphic message dispatch can replace conditionals by simply implementing them. Languages like Smalltalk, Self and Newspeak are existence proof of that, because those languages don't even have conditionals. (They also don't have loops, BTW, or really any sort of language built-in control structures except for polymorphic message dispatch aka virtual method calls.)

Pattern Matching (Haskell)

You could also define or using pattern matching, or something like Haskell's partial function definitions:

True ||| _ = True
_    ||| b = b

Of course, pattern matching is a form of conditional execution, but then again, so is object-oriented message dispatch.

ContentLicense: CC BY-SA 4.0


问:
Is it okay to use CSS3 with HTML4?
Is it alright to use CSS3 with HTML4.  It seems like CSS3 would be a HTML5 complaint deal.  But I'm not sure if that's the case.

If it's not okay,  what are the downfalls to using CSS3 with HTML4, opposed to CSS3 with HTML5?

答: Yes, to the extent that “CSS3” exists at all. “CSS3” is a collective name for a set of specifications and drafts at very different levels of maturity and implementation. There is no single CSS3 specification (like there is the CSS 2.1 specification), and probably never will. Thus, “to use CSS3” means very different things, ranging from well-defined universally implemented features to sketchy constructs with experimental or no implementations. Whether they work or not does not depend the least on whether you call your markup “HTML 4”, “HTML5”, or something else.</p>

Title: Is it okay to use CSS3 with HTML4?


问:
Can a process that needs 15 MB run given a machine with 10 MB of physical memory and 10 of virtual?
So there is physical and virtual memory. Let's say we have 10 MB physical and 10 MB virtual.

There is also paging. As far as I get it, paging basically splits physical and virtual memory into slots of the same size. Such slots are called frames. So if we use slots of 1 MB, we will have 10 frames in physical memory and 10 in virtual memory.

A process requires memory, and all such memory must be located in the physical side. If we load a process that needs 5 MB, then 5 frames in the physical side will be claimed for it.

If the process requires 15MB, then... 10 frames in physical memory are claimed, and 5 in virtual? But the process needs ALL its memory in the physical side, right? So the first question is:

Does this mean that a process that needs 15 MB cannot run on our machine, since only 10 MB fit in the physical side?

Alright. Let's say we have two processes. Each needs 8 MB. 8 frames in the physical side will be claimed for the first process, and 2 frames for the second. Then 6 frames in the virtual side will be claimed for the second.

Only one process can run at a time, so when it is the second process' turn, it needs to retrieve its 6 frames from the virtual side to the physical side. This will cause 6 frames of the first process to move from the physical side to the virtual. Is this correct?

答:
The entire point of virtual memory is to be able to run processes that require more RAM than you have RAM chip in your computer. If it couldn't do that, you wouldn't be any better off than without it.

As Robert Harvey has explained, the way of providing this capability is to intercept all memory accesses the process makes and loading them into physical memory as required. This works because even a process that requires a certain amount of memory will never actually read all of that memory simultaneously, so the OS, which already controls execution speed of that process via time-slicing, can also control the memory use of that process by only providing the bits it does actually access in any given time slice, rather than all the bits that it could access if it decided to.


问:
Is try-finally expensive
In case of code where you have to do a resource cleanup before exiting a function, is there a major performance difference between these 2 ways of doing it.

Cleaning the resource before every return statement

```<code>void func()
{
    login();

    bool ret = dosomething();
    if(ret == false)
    {
        logout();
        return;
    }

    ret = dosomethingelse();
    if(ret == false)
    {
        logout();
        return;
    }

    dootherstuff();

    logout();
}
</code>```

Cleaning the resource in a finally block

```<code>void func()
{
    login();

    try
    {
        bool ret = dosomething();
        if(ret == false)
            return;

        ret = dosomethingelse();
        if(ret == false)
            return;

        dootherstuff();

    }
    finally
    {
        logout();
    }
}
</code>```

I did some basic tests in sample programs and there doesn't seem to be much of a difference. I so much prefer the finally way of doing this - but I was wondering if it will cause any performance hit in a big project.

答:
As others already noted, Ttese code will have different results, if either dosomethingelse or dootherstuff throw an exception.

And yes, any function call can throw an exception, at least a StackOVerflowError! While it is rarly possible to handle these correctly (as any called cleanup function will probably have the same issue, in some cases (such as implementing locks for example) it is crucial to even handle that correctly...

Title: Is try-finally expensive


答:
The important thing to understand about virtual memory is that it's, um, virtual.

For example, a process might think it has 20 MiB of virtual memory. However, 5 MiB of that might be part of a memory mapped file that hasn't been loaded from disk, 5 MiB might look like a large area that's full of zeros (but might be the same tiny area full of zeros repeated over and over and over), 5 MiB might be data on the swap partition.

It's all virtual, which means it all looks like RAM is there (even when it's not).

When the process tries to access something that actually isn't there, the kernel is notified (e.g. "page fault") and does whatever it needs to do to maintain the illusion that the RAM was there all along.

For example, if the process reads some data from the area that's actually a memory mapped file, the kernel might load 4 KiB from the file into memory and let the process think the data was always there. If the process writes to that big area full of zeros then the kernel might allocate a new small area (and fill it with zeros) that the process can modify (without messing up other areas of zeros). In the same way, if the process tries to read/write to something that's currently in swap space, the kernel fetches it from swap.

To make this happen, the kernel might need more memory. When it runs out of memory, the kernel can just copy data to disk/swap space and re-use that memory. Of course if a copy of the data is already on disk (e.g. it wasn't modified since it was loaded from disk last time) the kernel doesn't even need to do that - it can just re-use the memory immediately.

So... You might have a process with 2 GiB of virtual space. In that 2 GiB of space the process might only be using 50 MiB of virtual memory. Of that 50 MiB of virtual memory, it might only be 10 MiB of actual RAM (and 40 MiB of "trickery").

Of course (because disk IO is slower than RAM) most of the tricks do effect performance. Kernels try to be smart and try to keep the "most likely to be used" data in memory to minimise the effect on performance. Sadly, predicting the future is hard, so "trying to keep the most likely to be used data in memory" typically ends up being more like "actually keeping the most recently used data in memory".

In any case, the best way to minimise the overhead is to have enough RAM. The more RAM you have, the less trickery the kernel needs to do, and the faster things go. Fortunately, most of the memory that most processes use isn't actually used very often, so (depending on the process) you can get by quite well with only half the RAM.

Also note that (in general) worse performance might be undesirable, but it can be a whole lot better than "process crashed due to out of memory".

Title: Can a process that needs 15 MB run given a machine with 10 MB of physical memory and 10 of virtual?

Body:
So there is physical and virtual memory. Let's say we have 10 MB physical and 10 MB virtual.

There is also paging. As far as I get it, paging basically splits physical and virtual memory into slots of the same size. Such slots are called frames. So if we use slots of 1 MB, we will have 10 frames in physical memory and 10 in virtual memory.

A process requires memory, and all such memory must be located in the physical side. If we load a process that needs 5 MB, then 5 frames in the physical side will be claimed for it.

If the process requires 15MB, then... 10 frames in physical memory are claimed, and 5 in virtual? But the process needs ALL its memory in the physical side, right? So the first question is:

Does this mean that a process that needs 15 MB cannot run on our machine, since only 10 MB fit in the physical side?

Alright. Let's say we have two processes. Each needs 8 MB. 8 frames in the physical side will be claimed for the first process, and 2 frames for the second. Then 6 frames in the virtual side will be claimed for the second.

Only one process can run at a time, so when it is the second process' turn, it needs to retrieve its 6 frames from the virtual side to the physical side. This will cause 6 frames of the first process to move from the physical side to the virtual. Is this correct?


问:
How does Yahoo's Smush.It work and why doesn't everyone use it?
I've recently come across an application by Yahoo called SmushIt. Apparently it does lossless compression on images. Sometimes the image size is reduced by as much as 90%. This of course has major implications when working on the web since it greatly improves performance on pages that have a lot of images. Now I'm sure there are other applications like this one out there but I've never heard of anyone actually doing lossless image compression in web development.

So I guess my questions are - how is it possible to reduce an image by 90% without losing quality and why isn't such a practice more popular in web development (if there exists a logical reason)?

答:
How is it possible to reduce an image by 90% without losing quality?

Formats and compression options

There are three popular image storage formats for web (not counting the promising WebP), and each format has its own compression options.

A clueless coder may pick the wrong format and use wrong options, resulting in less-than-optimal image quality and huge size. An experienced graphical designer is expected to know which format and options should be used, resulting in high quality images with low bandwidth footprint.

Let's see how it works.

Example 1: 90% reduction

The first example is a photo. Nearly every photograph is stored in JPEG, but an inexperienced coder may hear somewhere that PNG is the best format, and prefer using PNG. This is what happens:

Open image in new tab to see the full-size 2470×1636 version.

The size of this PNG image is 5 992 591 bytes—nearly 6 MB, enough to make both the server bandwidth and your customers unhappy.

Open image in new tab to see the full-size 2470×1636 version.

Here is the same image exported as JPEG. The JPEG compression level was thoughtfully adjusted to avoid losing visual quality: watching the images side by side, you normally can't tell which one is which.

The size of the JPEG image is 700 283 bytes, that is 683 KB: 11.7% compared to the PNG variant. We indeed achieved nearly 90% compression without affecting the quality of the image.

Example 2: 80% reduction

Now the clueless coder is convinced that JPEG images are much smaller than PNG ones, so he's using JPEG for everything. When he needs to store a logo, he chooses JPEG.

Open image in new tab to see the full-size 1300×850 version.

Since lower compression levels make JPEG artifacts noticeable, he should push the levels up to 100—lowest compression, highest file size. He obtains a 68 348 bytes file (67 KB).

A more experienced graphical designer prefers PNG. Here's the result.

Open image in new tab to see the full-size 1300×850 version.

By carefully adjusting the options, i.e. using a 8-bit PNG with 128 colors, he obtains the same visual result in a file which weights only 13 930 bytes (14 KB), that is 20.4% of the JPEG variant, that is a compression of approximately 80%.

Important notes about the examples

Although those examples show a difference of 80% to 90%, a really clueless coder may do worse. I knew people who were storing images in BMP format and were actually paid to create websites. There is always a way to screw things up and to achieve unnecessarily huge sizes without any visible gain in quality.

Having said that, both examples illustrate exactly what can actually happen when the website is done by inexperienced web designer or web developer.

The fact that many persons are using wrong tools makes things even worse. In those examples, I've used Photoshop to export the images in both formats. I would expect that different applications may perform differently when it comes to rendering final images, resulting eventually in poor quality coupled with excessive file size.

Why isn't such a practice more popular in web development?

Who is Smush.It actually for?

Since we now understand how formats and compression options work and how are they enabling us to reduce the size of an image by 80% or 90% without losing quality, let's see what is the actual value of Smush.It and who should use it.

Is it:

For large projects made by teams of highly specialized and skillful persons?

Probably not. Those persons can afford buying a Photoshop license and know what formats and options should they use for different images. They won't need Smush.It, because the size of their images is already as small as possible.

From there, either Smush.It will make some changes resulting in the loss of quality—something those persons want to avoid at all costs, or it will have no impact.

This is confirmed by the website itself, which is very unfriendly. As a developer, I don't want my images to be magically changed: I want to know what were the changes and all the magic which happened under the hood. I don't want to use voodoo services: I need to know exactly what happens with my images, especially in order to learn from that.

There might be some information on their FAQ page, but since it doesn't work, we'll never know.

Blogs are not helpful either. There is one blog which mentions a gain of 4.79%, but this would be practically unnoticeable on most websites. The only mention of what actually happened under the hood is that Smush.It switched from GIF to PNG—something the developers should have be doing on their own if only they knew formats and compression options.

For small projects made by inexperienced coders?

Indeed, those coders don't know how to store images in the first place and don't care about the magic under the hood.

But it's not for them either. Chances are, they simply don't care, and they have more important issues, such as the lack of client-side caching, the lack of CSS/JavaScript minification or the lack of Gzip compression.

The only two cases I can think of are:

An inexperienced programmer who wants to impress his boss. He doesn't know how to store images properly, but he knows that there is a tool which does all the voodoo magic for him. Result: he can make himself valuable in a company as a guy who was able to reduce the bandwidth because of his deep knowledge of online tools.

A boss who learned about a new tool and wants to use it everywhere.


答:
It could run in theory, but the ratio 15/10 is significant enough to probably make thrashing happens. If that is the case, the process could run many thousand times slower (because too often the kernel would fetch some page from the disk and pageout another page); if your disk is still a real rotating disk (not an SSD) it would make a lot of noise. Definitely, read the wikipage about virtual memory.

On some OSes, you could give hints to the virtual memory subsystems. For example, using madvise(2) on Linux, and posix_madvise on POSIX.

In practice, today's disks are so slow w.r.t. CPU and RAM (about a million times slower) that it does not make sense to have a working set larger than the available RAM. This was a bit less true in the 1980s (because at that time the speed ratio RAM vs disk was less high). I remember having (painfully) - circa 1987 - run a Lisp process of 15Mbytes on a 12Mbyte Sun3 : the disk (of the size of a washing machine) was vibrating a lot. The process ran about 20 times slower.

Read also about memory overcommit and http://linuxatemyram.com/

And today, the CPU cache matters a lot, perhaps even more that the page cache.

BTW, you could do some experiments on Linux, since you can limit the RAM used by a process (using setrlimit(2))


答: Having just tested it on a variety of images from a couple of web sites I maintain, I can state that I won't be using it because it seems to do nothing useful: it was unable to achieve any savings for any of the four images I gave it (two JPEGs and two PNGs). I had taken no special steps to optimize these images, just saving them in the most appropriate format directly from Photoshop.</p>

Title: How does Yahoo's Smush.It work and why doesn't everyone use it?

Body:
I've recently come across an application by Yahoo called SmushIt. Apparently it does lossless compression on images. Sometimes the image size is reduced by as much as 90%. This of course has major implications when working on the web since it greatly improves performance on pages that have a lot of images. Now I'm sure there are other applications like this one out there but I've never heard of anyone actually doing lossless image compression in web development.

So I guess my questions are - how is it possible to reduce an image by 90% without losing quality and why isn't such a practice more popular in web development (if there exists a logical reason)?


问:
Why does XMLHttpRequest not seem to follow a naming convention?
I've been working with the XMLHttpRequest object in JavaScript recently, and I couldn't help but notice that the casing of this name makes no sense.  Why is 'XML' all in caps while 'Http' is not?  They're both acronyms!

Surely it'd make more sense for the name to be one of the following:

XmlHttpRequest (PascalCase, best practice for class names in JavaScript)

xmlHttpRequest (camelCase, also common though not for classes)

XMLHTTPRequest (caps-for-acronyms, rarely used in programming?)

I'm sure there must be some reason and I'd hate to think it's now set in stone just because no one questioned this at the time.  Is there another naming convention that I'm unaware of?

答:
Some naming guidelines make a distinction between "short" and "long" acronyms. For instance, the coding style guide for Microsoft's .Net runtime specifies that short acronyms should be in block caps while long acronyms should only have the first letter capitalized. Their threshold for a long acronym is 3 letters, so would favor "XmlHttpRequest", however it is not unreasonable to think some people may use a similar rule with 4 characters as the threshold.

I've looked at old copies of the mozilla.org style guide, and none seem to specify anything about acronyms, but it's possible that either an older Netscape guide did, or that the developer was applying a rule he'd picked up elsewhere.


问:
Applying initialization-on-demand holder idiom at variable level rather than class
I was looking for the idiomatic way to implement thread-safe lazy initialization for a configuration collection retrieved from the DB inside a Spring bean.

I decided to adapt the initialisation-on-demand holder pattern as follows:

```<code>public class Security {

    private static ParametersDao DAO;

    /**
     * Initialisation-on-demand Holder pattern
     */
    private static class StaticHolder {

        public static final Set<String> VALID_EMAIL_ADDRESSES;

        static {
            VALID_EMAIL_ADDRESSES = DAO.loadEmailAddresses();
        }
    }

    private ParametersDao parametersDao;

    public void setParametersDao(ParametersDao parametersDao) {
        this.parametersDao = parametersDao;
    }

    public Set<String> getValidEmails() {
        if (parametersDao == null) throw TooSoonException();
        DAO = parametersDao;
        return StaticHolder.VALID_EMAIL_ADDRESSES;
    }
}
</code>```

What are the issues to watch out for adapting this approach like this, apart from the timing issue between needing the valid email addresses and IoC container initialisation?

答:
By storing state inside a static nested class, you are limiting yourself to only being able to instantiate a single instance of this object. If you ever need to use multiple DAO implementations, or add another dependency that needs to change, this could cause a problem. Such requirements seem to me to be quite likely in order to sufficiently unit test this code.

I'd suggest simply using a synchronized method and allocating the object if its reference is null, unless you have a good reason to believe the overhead of this approach would be too high.


问:
Is it good practice to inherit from generic types?
Is it better to use List<string> in type annotations or StringList where StringList

```<code>class StringList : List<String> { /* no further code!*/ }
</code>```

I ran into several of these in Irony.

答:
In principle there's no difference between inheriting from generic types and inheriting from anything else.

However, why on earth would you derive from any class and not add anything further?


问:
Is it better to use strings or int to reference enums outside the java part of the system?
We were having a discussion at my work about the use of enums in Java.

A coworker was arguing that when using enums on the server-side, whenever required we should use string to reference to it (for instance when sending data from JS to the server or when storing in the database), arguing that this is much more clearer for the developer and also arguing that it would fail fast in case of typos.

I always used integers to identify enums in these cases, because it would be immutable identifiers and would not have case and typo problems (even though if a dev made the mistake of using the value 2 instead of 1, it would not fail fast).

Being very analytic about these arguments, I would say that using strings is better, but I get a strange feeling about it (as if it was not a good approach).

Is there any best practice regarding this discussion that could guide me?

Edit: Whenever it is possible, we use the enum itself, so all our Java code uses the Enum. By "reference to an enum" I mean: referencing the value in the enum when exchanging data from JavaScript to the server or storing data in the database

答:
I agree with Neil's answer, but just an addition:

In java enums are Objects, so they can have fields and methods. So you can give each enum some manualy specified value and when referencing it for outside work, use that value instead.

It will survive both adding/removing/reordering and changing name of enum instance.
But you will have to write serialization/deserialization logic for enum fields instead of using automagic available in many tools. (Its easy, but its aditional work).

And you must keep those values unique manually (but that's same in C style enums), and you can write test to check that.


问:
memory management of multi-dimensional array
Could you please show me an example how to compute the location of an element in a multi-dimensional array.

It is illustrated in Robert Sebesta's book Concept of Programming Languages that location of an element is given by the formula

```<code>location(a[i,j]) = address_of(a[1,1]) + ((i - 1)*n + (j - 1))*element_size
</code>```

where n is the number of elements per row and a[1,1] is the base address (1-based indexing).

I tried to find the location of [5,5] in a 7×7-matrix, assuming element_size=2. By calculating manually I got the value as 66. But while calculating by using the formula I got the value as 64:

```<code>location(a[5,5]) = 0 + ((4*7) + 4)*2 = 64
</code>```

Is this correct or not? Could you tell me how the difference of two occurred.

答:
To me it's always 64. The location of 5,5 is 0+(((5-1)*7)+(5-1))*2= ((4*7)+4)*2= 28*2+4*2= 56+8= 64.

When you manually trying to calculate did you by any chance calculated the end address of the element at location 5,5 while you expected it's starting address? It's a common mistake, I'm asking because you didn't post how you calculated it manually.

00 02 04 06 08 10 12

14 16 18 20 22 24 26

28 30 32 34 36 38 40

42 44 46 48 50 52 54

56 58 60 62 64 66 68

70 72 74 76 78 80 82

84 86 88 90 92 94 96


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
See this succinct article: When IT Projects Go Right.

An absence of any of the elements stated in the article should set alarm bells ringing:

So make sure your project has all of the following, if not then you should be concerned:

(to quote the above article:)

"The first is that they are based on a clear vision of what is to be achieved."

"The second characteristic concerns the support and commitment of the different parties involved across the business, especially senior management."

"Third is an understanding of the problems to be tackled."

"The final common characteristic is that sufficient resources and skills have been made available."

ContentLicense: CC BY-SA 2.5


答:
Welcome to the wonderful world of middleware development. It can be a lot of hard work and debate to develop a protocol, and no one should ever see the results.

If you are on a small team, then avoid a dictator: have quick meetings with everyone to hammer out the protocol.

Medium sized teams may wish to have representatives that work out the protocol.

Large teams and/or teams with complex organization should have dedicated middleware people to control the protocol.

In all cases document! What are the preconditions, what are the post-conditions, what are required fields, what are optional fields, what are the side effects, what errors are returned… Keep the document living, when new conditions, error types, or side effects are found, then they get added to the document.

I would also recommend both client and server side unit-tests and system tests to ensure conformance to the document.

It may seem like a lot of work, but minor missteps here can be very expensive and time consuming.

Title: Should a front-end developer ever specify JSON format for back-end developers?

Body:
I am taking the front-end role in a project. Should I be specifying for my back-end teammates the exact format of JSON that their PHP returns to my JavaScript?

For example, should I be telling them they should use a format similar to one described here:

Proper way to structure JSON for front-end consumption

Or should I keep my role as sterile as possible, and simply describe in words the inputs and outputs I need from their back-end interface? (Of course, if this happens it might be more difficult on my part to handle their different data structure formats)


问:
(jQuery) What is wrong with methods such as .append?
tl;dr: What is wrong with the efficiency of methods such as .append() and what can be alternatives to this?

Explanation:
Hello everyone. I occasionally have to build A/B tests for websites, which means that i have to change sites using only jQuery(or javascript of course) to alter appearances and functionalities of websites. This means no 'hard'-html/css or the likes. Now i'm pretty much the only one with the slightest knowledge of javascript that works here, so i don't get much peer reviews. Now we are working with a customer and their developer sends me this feedback:

'jQuery isn't used optimally by appending seperate/loose items into the DOM'.

An example of this is an accordeon item i added to the site, by typing (something along the lines of):

```<code>$('#site_container').append('<div id="container"><div id="container_click">Content to click on</div></div id="container_expand">Content to be shown when expanded</div></div>');
$('#container_click').click(function(){//animate to height function here});
</code>```

Now i've already tried to do my own research, and i know typing an entire element with it's content in 1 string is not as secure as making an object and then adding attributes to that object. For a temporary test however, i do not think this is such a big issue, since they only tend to live for a week or 2.

I do realise the solution feels a bit flimsy, but i do not really see a different approach.

Now my question is: What does the other developer mean with optimally? Is there a big part of jQuery i'm missing? Is there a way to approach problems like these more efficiently?

答:
What they probably meant is that manipulating the DOM is slow and that you can avoid injecting HTML through jQuery.

What you can do, instead, is to have A/B variants both in your original HTML. Then, you hide the B variant by default, and switch from A to B by simply hiding the one and showing the other.

An even better alternative is to have two HTML templates, one for A variant, another one for B. This way, you don't even need to rely on JavaScript.

Performance-wise, I'm not sure if you need to take in consideration their remark. Unless you're doing a lot of DOM manipulation, you .append() maybe slows down the page by a few milliseconds or even microseconds. Unless you've profiled the app and determined that your .append() is the actual bottleneck, don't bother.

You may, on the other hand, be interested by 43,439 reasons to use append() correctly blog article and by .append VS .html VS .innerHTML performance answer on Stack Overflow.


问:
Is there any algorithm pattern to protect any content in the web to ensure I am the first one who created it?
A few years ago there was this hacker (don't remember who he was) that full disclosed a vulnerability in a given system, but to make sure nobody took credit for that, he created some kind of PGP key.

What I understood at the time is that he created a key to ensure he was the one who discovered it, but didn't disclosed who he was actually, just created some mechanism to be able to prove that he was the one who created the disclosure.

Ok. I get how algorithms and cryptography works. But I still don't understand how you can create a key to protect a given content disclosed in the web to prove you are the one who created it first! It is just words!

Is it really possible? What should be the process to ensure you can empirically prove it? Did I understood it correctly or I probably missed something regarding this case?

I hope this question is specific enough, basically it is just how to protect a content that you created in the web (a paragraph, a code, a word, etc.) and make sure you are the one who created it first, inside a given context.

With my knowledge I don't see how that is possible, but I am intrigued if there is a practical way to do it. Is there?

答:
I probably missed something regarding this case?

I think the bit you are missing is a trusted entity.

When you hash the file with the content you want to certify, you can show to the world that you are the owner of this document, without disclosing this document. This is all very well, but how can you prove you had this document at some specific time in the past ?

This is what Trusted Timestamping is about. Here is an extract from wikipedia:

The technique is based on digital signatures and hash functions. First
  a hash is calculated from the data. A hash is a sort of digital
  fingerprint of the original data: a string of bits that is different
  for each set of data. If the original data is changed then this will
  result in a completely different hash. This hash is sent to the TSA*.
  The TSA concatenates a timestamp to the hash and calculates the hash
  of this concatenation. This hash is in turn digitally signed with the
  private key of the TSA. This signed hash + the timestamp is sent back
  to the requester of the timestamp who stores these with the original
  data (see diagram).

(*) Time Stamping Authority

I have been using Universign's Timestamping Service, which has a nice set of tools to make the whole operation easy to perform. There are plenty of companies offering similar services.

It is interesting to note that, as @JoelFan mentioned, that bitcoin provides a way to get a trusted entity that is not centralized (why should I trust anyone ?). The bitcoin chain provides a timeline (you can prove one document incrusted in the bitcoin chain was created before another further down in the chain). To my understanding, however, you would still miss the effective date and time of the event.

Also, Trusted Timestamping is a valid reference in litigation.


问:
Why use a enum to create the singleton pattern
Why would you use an enum to create a singleton pattern?
To what purpose would it serve over a conventional singleton pattern?

I have seen the above used. The code uses an enum to create this pattern without benefit. It confuses the situation as the enum is not used to store a "set of named integral constants" but simply a method.

答: You wouldn't use it.  It's mainly out there as an exercise to help you understand the interesting properties of java enums, for which there are a few uses beyond the more traditional C++ style uses.  It's less verbose and requires some relatively deep knowledge of the language, which makes it attractive to the "look how clever I am" breed of programmers.  You don't want to be that guy.</p>


答:
I'd say it is not good practice.

List<string> communicates "a generic list of strings". Clearly List<string> extension methods apply. Less complexity is required to understand; only List is needed.

StringList communicates "a need for a separate class". Maybe List<string> extension methods apply (check the actual type implementation for this). More complexity is needed to understand the code; List and the derived class implementation knowledge is required.

Title: Is it good practice to inherit from generic types?

Body:
Is it better to use List<string> in type annotations or StringList where StringList

```<code>class StringList : List<String> { /* no further code!*/ }
</code>```

I ran into several of these in Irony.


答:
In addition to all the programmed solutions using the if construct, it's possible to construct an OR gate by combining three NAND gates.  If you want to see how it's done in wikipedia, click here.

From this, the expression,

NOT[ NOT( A AND A ) AND NOT( B AND B )]

which uses NOT and AND gives the same answer as OR.  Notice that the use of both NOT and AND is just an obscure way of expressing NAND.

Title: How to define "or" logically

Body:
Recently, I came across a problem that required me to define the logical "OR" operator programmatically, but without using the operator itself.

What I came up with is this:

OR(arg1, arg2)
  if arg1 = True and arg2 = True
     return True

  else if arg1 = True and arg2 = False
     return True

  else if arg1 = False and arg2 = True
     return True

  else:
     return False
```

Is this logic correct, or did I miss something?


答:
I don't know C# very well, but I believe this is the only way to implement a typedef, which C++ programmers commonly use for a few reasons:

It keeps your code from looking like a sea of angle brackets.

It lets you swap out different underlying containers if your needs change later, and makes it clear you reserve the right to do so.

It lets you give a type a name that is more relevant in context.

They basically threw away the last advantage by choosing boring, generic names, but the other two reasons still stand.


问:
In a REST based system should a request for a sub-resource include the parent
I'm unsure of REST best practise in the following scenario:

GET /Customer/23 = returns Customer = OK

GET /Customer/23/Orders

In the second request should a Customer AND the Orders be returned, or should just the Orders be returned?

答:
One of the principles in REST is that you have one URL to retrieve a particular resource through. For "Customer 23", this URL is /Customer/23.

If you start returning the Customer resource also from /Customer/23/Orders, you suddenly have two URLs to retrieve that Customer resource, with the associated questions what the difference is between those two Customer resources.

For that reason, /Customer/23/Orders should only return the resource that represents a list of orders.


问:
"positively formulated" vs. "reads as english sentence" style logic
Sorry, I'd be happy to have someone improve the title of this question.

What are the benefits and downsides of "positively formulated" logic vs. having it "english readable". I'm looking for a generic position that can be placed into code guidelines.

Examples of what I see as "positively formulated" logic

```<code>if ($obj->isValid()){

if ($found){

if ($first){
    //do nothing
}else{
    doX();
}

$this->useFields(array('a','b'));
</code>```

Examples of what I see as "negatively formulated" logic

```<code>if (!$first)
    doX();
}

$this->unset(array('d','e','f','g'));
</code>```

Whereas if focusing on "English readable" I would see this as good:

```<code>if (isValid()){

if ($found){
</code>```

and this is not "English readable"

```<code>if ($l){

if (isValid() || !isActive()){
    doX();
}
</code>```

答:
I would go with negative logic.

Well, you have something here...
The issue is not with the ability to read it in a given language but in the process beneath.

Going "negative logic" simplifies the process.

If you have a single layered condition then the benefits are to be drawn from the names of the procedures, like isValid, isFound, as you pointed out.

However the major benefit becomes visible below, if you choose to go with negative logic and not to use nested ifs:

if c1:

        work1t

        if c2:

                work2t

                if c3:

                        work3t

                else:

                        work3f

        else:

                work2f

else:

        work1f

vs.

if ! c1:

        work1f

work1t

if ! c2:

        work2f

work2t

if ! c3:

        work3f

work3t

Instead of having a bushy structure that can only grow and that quickly turns into a nightmare to maintain, we now have a constant depth flow that can be manipulated fairly easy.

It is the same idea as with sanitization, we don't work unless all the parameters are valid, just that we sanitize the process.

This reduced complexity transcends any natural language as it is pure logic. I think that English readable is an appalling title. Stay away of natural languages. They are horrific because you start to talk to the computer and you end up with tons of inefficient code.
You could go with something quantifiable like keeping the cyclomatic and NPath complexity of the class/method under a certain level.


答:
I can think of at least one practical reason.

Declaring non-generic types that inherit from generic types (even without adding anything), allows those types to be referenced from places where they would otherwise be unavailable, or available in a more convoluted way than they should be.

One such case is when adding settings through the Settings editor in Visual Studio, where only non-generic types seem to be available. If you go there, you'll notice that all System.Collections classes are available, but no collections from System.Collections.Generic appear as applicable.

Another case is when instantiating types through XAML in WPF. There is no support for passing type arguments in the XML syntax when using a pre-2009 schema. This is made worse by the fact that the 2006 schema seems to be the default for new WPF projects.


答:
In some cases it is impossible to use generic types, for example you can't reference a generic type in XAML. In these cases you can create a non-generic type which inherits from the generic type you originally wanted to use.

If possible, I would avoid it.

Unlike a typedef, you create a new type.
If you use the StringList as an input parameter to a method, your callers can't pass a List<string>.

Also, you would need to explicitly copy all constructors you whish to use, in the StringList example you couldn't say new StringList(new[]{"a", "b", "c"}), even though List<T> defines such a constructor.

Edit:

The accepted answer focuses on the pro's when using the derived types inside your domain model. I aggree that they can potentially be useful in this case, still, I personally would avoid them even there.

But you should (in my opinion) never use them in a public API because you either make your caller's life harder or waste performance (I also don't really like implicit conversions in general).


问:
REST-ful design: recommended approach for fetching related entities
Suppose I have two entities author and post, were every post has an author.
Implemented are these REST calls

Get a paginated list of posts: GET /posts?page={page}

Get a list of authors: GET /authors

Get a single author: GET /authors/{id}

Suppose I also have a client using the REST service. This client wants to show a paginated list of posts with related authors.

Now how would the REST service work regarding the related entities? There are the following methods:

Let the GET /posts?page=1 call return the posts and the related authors in a single call. Optionally make this a separate parameter, f.e. GET /posts?page=1&related=true or GET /posts/related?page=1.

Let the client loop through the posts and get the author for every post using the GET /author/{id} call.

Let the REST call for the authors accept a list of ID's as a filter, so the client can get the related authors in one call, f.e. GET /authors?ids=10,12,16,30,43,44,58.

Method 1 is the easiest one from the client's perspective since it gets all the necessary data in one call. But the REST service is limited here, it shouldn't need to fit any particular client because every client has other requirements.

Method 2 is the cleanest REST approach, but let's say that a page has 30 posts, the client has to make 30 additional REST calls to retrieve the related authors. This is very inefficient.

Method 3 is perhaps better of the three, since it is a relatively clean REST implementation (compared to method 1) and it requires only one extra call per page.

Is there a recommended approach here?

答:
You could do something similar to what discogs do in their API, http://www.discogs.com/developers/#page:database,header:database-release.
When requesting a release /releases/{release_id} the response also includes a subset of artist data, extract from the response body:

```<code>{
    "title": "Never Gonna Give You Up",
    "id": 249504,
    "artists": [
        {
            "anv": "",
            "id": 72872,
            "join": "",
            "name": "Rick Astley",
            "resource_url": "https://api.discogs.com/artists/72872",
            "role": "",
            "tracks": ""
        }
    ]
}
</code>```

In your case instead of artists it could be author and if the client want more info on the author they should of course use GET /authors/{id}.

Body:
You could do something similar to what discogs do in their API, http://www.discogs.com/developers/#page:database,header:database-release.
When requesting a release /releases/{release_id} the response also includes a subset of artist data, extract from the response body:

{
    "title": "Never Gonna Give You Up",
    "id": 249504,
    "artists": [
        {
            "anv": "",
            "id": 72872,
            "join": "",
            "name": "Rick Astley",
            "resource_url": "https://api.discogs.com/artists/72872",
            "role": "",
            "tracks": ""
        }
    ]
}

In your case instead of artists it could be author and if the client want more info on the author they should of course use GET /authors/{id}.


问:
Using WebStorm for Razor Syntax MVC
I am building a lot of client-side heavy SPA-like apps with VS2010 and MVC3/4.  VS2010 Javascript/HTML/CSS editing (mostly javascript) is interminably slow and sluggish.  I'd love to use something like JetBrains' WebStorm to edit my .CSHTML files (with embedded javascript, etc. because I am using RAzor to pop in URL names, etc.)

WebStorm seems to have all of the things I want.. better language recognition ("intellisense") and the ability to integrate additional outside libraries into this (I'm using Kendo), etc.

Is this possible?  How do you get WebStorm to recognize the @"" invoked Razor language inserts?

Any help or suggestions would be appreciated.

答:
I am getting HTML and JavaScript autocompletion for *.cshtml files in WebStorm like this:

All I did was to register '*.cshtml' as html files under Settings | Editor | File Types
See: https://www.jetbrains.com/webstorm/help/file-types.html

Title: Using WebStorm for Razor Syntax MVC


答:
I think you need to look into some history.

C# has been used for a lot longer than it has had generic types for.

I expect that the given software had its own StringList at some point in history.

This may well have been implemented by wrapping an ArrayList.

Then someone a to refactoring to move the code base forward.

But did not wish to touch 1001 different files, so finish the job.

Otherwise Theodoros Chatzigiannakis had the best answers, e.g. there are still lots of tools that do not understand generic types.   Or maybe even a mix of his answer and history.


问:
Is it OK to partially change a collection with PUT or DELETE?
I have a collection of products in a product group e.g.:

```<code>product-groups/123/products
</code>```

If I need to add to the collection, is it OK that I pass only some products with PUT?

If I need to delete some products from the collection, is it OK that I pass filter data (an array of ID's) with DELETE?

What's the best way to implement the functionality in the spirit of ReST?

Edit: the items are links to separate entities, basically ID's of products.

答:
Just to precise previous answers / comments.

As per my knowledge, POST is the method to add single elements to the collection.

DELETE in turn, is the method to delete single element from the collection. Both scenarios are perfectly RESTful.

However, you should use appropriate URI to refer single element or the whole collection.

For example, to add element to collection you should POST data to following URI:

https://example.com/products/

To delete single product from the collection, you could use DELETE method sending request to something like:

https://example.com/products/108/

The PATCH method can be used to update some elements within the collection. For instance, when you only need to update one field in one element. PUTting a complete resource representation for very large collection can be very costly operation.


问:
Why are Scala's Either and Option types not interfaces/traits but classes?
I wanted to create a class CompileResult, that can be treated like an Either type but has some additional useful methods. It should be a CompileSuccess or a CompileFailure (which, too, has some extended functionality). However I can't do that because Either is an abstract class and I don't want to extend it but rather use delegation and have an Either stored internally.

So my question is, why is Either an abstract class now (also why was it a trait before) and why did they not use an interface? Same goes for Option too.

答:
The change to Either was made on April 24th, 2008 in commit c0b21797bde81861305dd68853add2d8bd46e484 "Changed isLeft and isRight to use less memory.":

Changed isLeft and isRight to use less memory.

Changed either from a sealed trait to a sealed abstract class to allow
  exhaustiveness checking.

All changes per the discussion in #797.

The referenced bug report is SI-797 "lazy vals on Either should probably be defs":

This comment by David R. MacIver is most illuminating:

While I'm making suggestions, wouldn't it be better if Either were a sealed abstract class so you could get pattern match warnings?

Note that in the meantime, Scala actually does support exhaustiveness checks for sealed traits as well as sealed abstract classes, so this would no longer be necessary, however, there is also this comment by Geoffrey Alan Washburn:

Given that Left and Right are final, I cannot see any sensible way someone could be using Either as a mixin.

So, it still makes sense for Either not to be a trait.

As for Option, it was sealed in commit 0bef86d8e8b7ea7ebb790ebcec7fedcb9a24f5a8 on March 9th, 2006, however, it was an abstract class even before then.

The change from trait to abstract class was made in commit d7007f7a9607481eb73b8df587e3c52cf4272147 "Use 'mixin class' instead of 'trait'" on March, 3rd, 2006.

As for why they aren't interfaces, the answer to that is rather simple: Scala doesn't have interfaces, at least not in the sense of Java or C#.


问:
C# static practices coming from dynamic background
I have been dappling in C# after coming from several years in PHP.
I don't find the language particularly difficult, although there are considerably more constructs for me to get used to.

My question is to help me change way of thinking when using C#.  More specifically, to help me think of solutions in a static language when I've been spoiled by a dynamic one.

For my experiment I have created a simple copy of Symfony's EventDispatcher, which is used as so:

```<code>// PHP
class Sample
{
    public function __construct()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener("sample.event", array($this, "onEvent"));
        $dispatcher->dispatch   ("sample.event", new Event());
    }

    public function onEvent(Event $event)
    {
        echo "Event Dispatched";
    }
}
</code>```

And this is my C# replica of EventDispatcher:

```<code>// C#
public delegate void EventListener (EventArgs args);

public class EventDispatcher
{
    protected Dictionary<string, EventListener> Listeners = new Dictionary<string, EventListener> ();

    public void AddListener (string eventName, EventListener listener)
    {
        EventListener l;
        Listeners.TryGetValue (eventName, out l);

        if (null == l) {
            l = listener;
            Listeners.Add (eventName, l);
        } else {
            l += listener;
        }
    }

    public void Dispatch(string eventName, EventArgs args)
    {
        EventListener listener;
        Listeners.TryGetValue (eventName, out listener);

        if (null != listener) {
            listener (args);
        }
    }
}
</code>```

And finally this is a copy of the PHP example:

```<code>// C#
class Application
{
    protected static EventDispatcher Dispatcher = new EventDispatcher();

    public static void Main(string[] args)
    {
        Dispatcher.AddListener ("sample.event", onEvent);
        Dispatcher.Dispatch    ("sample.event", new ErrorEventArgs(new Exception()));
    }

    public static void onEvent(EventArgs args)
    {
        Console.Out.WriteLine ("Event Dispatched");
    }
}
</code>```

Now the difference here is I am dispatching the event with ErrorEventArgs, a child class of EventArgs.  This is fine because the instance is substituted.

However, in PHP I can declare the listener as this to make certain the correct event is given to the method:

```<code>// PHP
public function onEvent(ErrorEvent $event)
{
    echo "Event Dispatched";
}
</code>```

However the same in C# will not work:

```<code>// C#
public static void onEvent(ErrorEventArgs args)
{
    Console.Out.WriteLine ("Event Dispatched");
}
</code>```

Because it does not match the delegate delegate void EventListener (EventArgs args).

Now I know .NET already has an event system and it looks like I am reinventing the wheel, also if you are familiar with Symfony2 you will know that it's event dispatcher is not a typical example of itself (events are usually globalized).

I could in this case only define the methods to conform with the required delegate and use introspection to determine whether the event should be handled.  Or I can implement AddListener and Dispatch as generic methods, at the cost of defining the dictionary as Dictionary<string, object>.

So my question boils down to whether I am approaching this the wrong way, whether this type of semi-dynamic programming is suitable, or is there a truely static way of implementing this?

Please bare in mind that this is an example experiment and in the real world I would look for traditional practices to implement this specific scenario.

EDIT:

Using the generics and object dictionary solution, here is the refactor:

```<code>public delegate void EventListener<T> (T args);

public class EventDispatcher
{
    protected Dictionary<string, object> Listeners = new Dictionary<string, object> ();

    public void AddListener<T> (string eventName, EventListener<T> listener)
    {
        EventListener<T> l;
        object obj;

        if (Listeners.TryGetValue (eventName, out obj)) {
            l = (EventListener<T>)obj; // handling required here if obj cannot be casted.
            l += listener;
        } else {
            l = listener;
            Listeners.Add (eventName, l);
        }
    }

    public void Dispatch<T> (string eventName, T args)
    {
        EventListener<T> l;
        object obj;

        if (Listeners.TryGetValue (eventName, out obj)) {
            l = (EventListener<T>)obj;
            l (args);
        }
    }
}
</code>```

答:
One of the most important things when using a programming language is understanding what it's weaknesses are. As many languages have substantially different weaknesses, it is often a very bad idea to directly port code from one to another.

In both examples you have provided, you are presented with a fairly severe typing issue. Even the dictionary has a large weakness, because you can pass in any key with any type, meaning that failed casts are likely.

If I understand what your goal was, you are trying to build a system for events that work through subscriptions and publishing. The best example I've seen of this is PRISM's EventAggregator. It works something like this:

```<code>public class EventAggregator : IEventAggregator
{
  private List<PubSubEvent> events;
  public T Get<T>() where T : PubSubEvent, new()
  {
    var matchingEvent = events.OfType<T>.FirstOrDefault()
    if(matchingEvent != null)
      return matchingEvent;
    matchingEvent = new T();
    events.Add(matchingEvent);
    return matchingEvent;
  }
}
</code>```

Where the PubSubEvent is something like this:

```<code>public abstract class PubSubEvent
{
  private List<Action> actions;
  public void Publish()
  {
    foreach (var action in actions)
      action();
  }
  public void Subscribe(Action action)
  {
    actions.Add(action);
  }
}
</code>```

In practice, the Get on the event aggregator is static, but I prefer dependency injection if possible. You may not even need the aggregator if you have good dependency injection. The pub sub event is also a bit different, because the PRISM versions take arguments, which is more like what you want. That project is open source, so you may as well look at it.

In any case, an event may be a simple, empty subclass, because the most important thing is the type name. Each event handles it's argument type, and if you want to subscribe to multiple events, you import multiple events.

Using MEF for dependency injection, for instance, you might do something like this:

```<code>[ImportingConstructor]
public SomeClass(DatabaseChangedEvent changedEvent)
{
  changedEvent.Subscribe(ReloadData);
}
private void ReloadData()
{
  ...
}
</code>```

So it's important to think about whether or not you even need all your events to be managed by the same object. It may make far more sense to only have any access at all to the exact events you need. There are many ways to do it. You can easily make the base event class generic, where the generic type is the argument class, and every subclass specifies it specifically. That would be an easy solution.

You generally don't need global things in C#, and static typing can help you quite a bit if you don't try to fight against it.

Body:
One of the most important things when using a programming language is understanding what it's weaknesses are. As many languages have substantially different weaknesses, it is often a very bad idea to directly port code from one to another.

In both examples you have provided, you are presented with a fairly severe typing issue. Even the dictionary has a large weakness, because you can pass in any key with any type, meaning that failed casts are likely.

If I understand what your goal was, you are trying to build a system for events that work through subscriptions and publishing. The best example I've seen of this is PRISM's EventAggregator. It works something like this:

public class EventAggregator : IEventAggregator
{
  private List<PubSubEvent> events;
  public T Get<T>() where T : PubSubEvent, new()
  {
    var matchingEvent = events.OfType<T>.FirstOrDefault()
    if(matchingEvent != null)
      return matchingEvent;
    matchingEvent = new T();
    events.Add(matchingEvent);
    return matchingEvent;
  }
}

Where the PubSubEvent is something like this:

public abstract class PubSubEvent
{
  private List<Action> actions;
  public void Publish()
  {
    foreach (var action in actions)
      action();
  }
  public void Subscribe(Action action)
  {
    actions.Add(action);
  }
}

In practice, the Get on the event aggregator is static, but I prefer dependency injection if possible. You may not even need the aggregator if you have good dependency injection. The pub sub event is also a bit different, because the PRISM versions take arguments, which is more like what you want. That project is open source, so you may as well look at it.

In any case, an event may be a simple, empty subclass, because the most important thing is the type name. Each event handles it's argument type, and if you want to subscribe to multiple events, you import multiple events.

Using MEF for dependency injection, for instance, you might do something like this:

[ImportingConstructor]
public SomeClass(DatabaseChangedEvent changedEvent)
{
  changedEvent.Subscribe(ReloadData);
}
private void ReloadData()
{
  ...
}

So it's important to think about whether or not you even need all your events to be managed by the same object. It may make far more sense to only have any access at all to the exact events you need. There are many ways to do it. You can easily make the base event class generic, where the generic type is the argument class, and every subclass specifies it specifically. That would be an easy solution.

You generally don't need global things in C#, and static typing can help you quite a bit if you don't try to fight against it.


问:
Passing a Context around with dependency injection
In the project I'm working on, I'm using Guice and trying to do as much as possible with Dependency Injection. However, there's one little snag; many of my objects rely on an object Context. This is an immutable object but has some information which most of the other objects need to function properly. It never changes for classes that are all working within the same Context, but my application must be able to support different Contexts at the same time, in the same scope. I can think of three ways to solve my problem:

Currently, I've found myself writing lots of code with AssistedInject, which almost always has methods like Factory.create(Context c). All my code that depends on Context is being created in this manner, even if they are otherwise simple.

I'm starting to consider using Providers, and changing every line of factory.create(context) to obj = provider.get(); obj.setContext(c); but I don't want to rely on my code to do both calls, I like that the compiler makes sure that every object has it's context and that the context cannot change (it never will).

My research pointed me to this thread: https://stackoverflow.com/questions/16316719/guice-assisted-injection-deeper-down-the-dependency-hierarchy The idea of pairing each Context to a childInjector which has one line bind(Context.class).toInstance(ContextFactory.makeInstance(args)), but I'm not sure how to ensure that everything is using the correct child injector. This seems like it might be best, but other than that thread (which isn't my scenario) I'm not sure how to do it, or if it's right for my situation.

Here's an sscce of what might be done by option 3:

```<code>public class GuiceChildTest {
    public static void main(String... args) {
        Injector inj = Guice.createInjector(new ParentModule());
        Injector fooChildOne = inj.createChildInjector(new FooModule(new Foo(10)));
        Injector fooChildTwo = inj.createChildInjector(new FooModule(new Foo(20)));

        Bar bar = fooChildOne.getInstance(Bar.class);
        System.out.println(bar.baz());

        bar = fooChildTwo.getInstance(Bar.class);
        System.out.println(bar.baz());
    }

    private static class ParentModule extends AbstractModule {
        @Override
        protected void configure() {
        }
    }

    private static class Bar {
        private MyInterface intf;
        @Inject
        public Bar(MyInterface in) {
            this.intf = in;
        }

        public int baz() {
            return intf.doSomething();
        }
    }

    private static class FooModule extends AbstractModule {
        private Foo f;
        public FooModule(Foo f) {
            this.f = f;
        }

        @Override
        protected void configure() {
            bind(MyInterface.class).toInstance(f);
        }
    }

    private static class Foo implements MyInterface {
        private int i;
        public Foo(int i) {
            this.i = i;
        }
        @Override
        public int doSomething() {
            return i;
        }
    }

    private static interface MyInterface {
        int doSomething();
    }
}
</code>```

答:
Let's address the fundamentals of Dependency Injection with a brief review of the dependency injection principle

When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (i.e. reversed), thus rendering high-level modules independent of the low-level module implementation details. The principle states

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend on details. Details should depend on abstractions.

It appears that the first two approaches you mentioned may not be fully following DI principles because the higher order objects appear to need to know what type of Context they should have.

And before I continue, I should admit a bias that will potentially offend fanatical DI proponents:

 DI can get over-emphasized and zealous adherence to the principles can get in the way of writing maintainable code that's appropriate for the environment that it operates within.  And that's not necessarily a dig against DI, but rather against any technique that ends up being blindly applied.  I'm not saying that you are blindly applying DI, but there are many who fall into that category.

Spoiler used to protect those who are overly sensitive to such claims

So before calling methods 1 & 2 "bad", we need to ask if they are meeting your current needs.  Those approaches involve some measure of boilerplate code that's copied around.  This can be okay if you don't find yourself needing to change that template on a frequent basis.

Likewise, if the objects can use one and only one type of Context, then you may not need to worry about DI in this case as there isn't necessarily something else you'd inject into the object.  "But what about testing?!" is the usual retort to that pragmatic claim, which is answered with an equally pragmatic answer of "Can those objects use / do they need a different Context for testing?"  If yes, then use DI.  If not, then ... carry on.

The 3rd option you propose gets you further away from the boilerplate code and gets you closer to a DI approach.  Your hesitation appears to be:

but I'm not sure how to ensure that everything is using the correct child injector

I think the solution to that challenge is to wrap your Context creation within a Factory and absolve the higher order objects from knowing what they need to call.

So if I understood your code sample correctly, instead of this:

```<code>Bar bar = fooChildOne.getInstance(Bar.class);
</code>```

you would have something like:

```<code>Bar bar = new Bar(ContextFactory.getInstance(Bar.class));
</code>```

In the suggestion, we're passing the Context returned from the ContextFactory into Bar's constructor.  It may be 1 trivial to simplify that example with:

```<code>public class Bar(){
    Bar(){
        return Bar(ContextFactory.getInstance(Bar.class));
    }
}
</code>```

or:

```<code>public class Bar(){
    Bar(){
        this.Context = ContextFactory.getInstance(Bar.class);
    }
}
</code>```

1 My Java is rusty, so I don't know if you can chain constructors like that first example.

And you could potentially tighten things up a bit by using reflection within the ContextFactory to determine the correct Context for Bar or optionally pass in additional parameters to the ContextFactory if Bar can handle multiple types of Context in regular operation.

TL;DR

Use the third option you proposed and wrap Context creation within a Factory.

Body:
Let's address the fundamentals of Dependency Injection with a brief review of the dependency injection principle

When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (i.e. reversed), thus rendering high-level modules independent of the low-level module implementation details. The principle states

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Abstractions should not depend on details. Details should depend on abstractions.

It appears that the first two approaches you mentioned may not be fully following DI principles because the higher order objects appear to need to know what type of Context they should have.

And before I continue, I should admit a bias that will potentially offend fanatical DI proponents:

 DI can get over-emphasized and zealous adherence to the principles can get in the way of writing maintainable code that's appropriate for the environment that it operates within.  And that's not necessarily a dig against DI, but rather against any technique that ends up being blindly applied.  I'm not saying that you are blindly applying DI, but there are many who fall into that category.

Spoiler used to protect those who are overly sensitive to such claims

So before calling methods 1 & 2 "bad", we need to ask if they are meeting your current needs.  Those approaches involve some measure of boilerplate code that's copied around.  This can be okay if you don't find yourself needing to change that template on a frequent basis.

Likewise, if the objects can use one and only one type of Context, then you may not need to worry about DI in this case as there isn't necessarily something else you'd inject into the object.  "But what about testing?!" is the usual retort to that pragmatic claim, which is answered with an equally pragmatic answer of "Can those objects use / do they need a different Context for testing?"  If yes, then use DI.  If not, then ... carry on.

The 3rd option you propose gets you further away from the boilerplate code and gets you closer to a DI approach.  Your hesitation appears to be:

but I'm not sure how to ensure that everything is using the correct child injector

I think the solution to that challenge is to wrap your Context creation within a Factory and absolve the higher order objects from knowing what they need to call.

So if I understood your code sample correctly, instead of this:

Bar bar = fooChildOne.getInstance(Bar.class);

you would have something like:

Bar bar = new Bar(ContextFactory.getInstance(Bar.class));

In the suggestion, we're passing the Context returned from the ContextFactory into Bar's constructor.  It may be 1 trivial to simplify that example with:

public class Bar(){
    Bar(){
        return Bar(ContextFactory.getInstance(Bar.class));
    }
}

or:

public class Bar(){
    Bar(){
        this.Context = ContextFactory.getInstance(Bar.class);
    }
}

1 My Java is rusty, so I don't know if you can chain constructors like that first example.

And you could potentially tighten things up a bit by using reflection within the ContextFactory to determine the correct Context for Bar or optionally pass in additional parameters to the ContextFactory if Bar can handle multiple types of Context in regular operation.

TL;DR

Use the third option you proposed and wrap Context creation within a Factory.


问:
Are all magic numbers created the same?
On a recent project, I needed to convert from bytes to <s>kilobytes</s> kibibyte. The code was straightforward enough:

var kBval = byteVal / 1024;
```

After writing that, I got the rest of the function working & moved on.

But later on, I started to wonder if I had just embedded a magic number within my code. Part of me says it was fine because the number is a fixed constant and should be readily understood. But another part of me thinks it would have been super clear if wrapped in a defined constant like BYTES_PER_KBYTE.

So are numbers that are well known constants really all that magical or not?

Related questions:

When is a number a magic number? and Is every number in the code considered a "magic number"? - are similar, but are much broader questions than what I'm asking.  My question is focused on well-known constant numbers which is not addressed in those questions.

Eliminating Magic Numbers: When is it time to say "No"? is also related, but is focused on refactoring as opposed to whether or not a constant number is a magic number.

答:
Not all magic numbers are the same.

I think in that instance, that constant is OK. The problem with magic numbers is when they are magic, i.e. it is unclear what their origin is, why the value is what it is, or whether the value is correct or not.

Hiding 1024 behind BYTES_PER_KBYTE also means you don't see instantly if it is correct or not.

I would expect anyone to know immediately why the value is 1024. On the other hand, if you were converting bytes to megabytes, I would define the constant BYTES_PER_MBYTE or similar because the constant 1,048,576 isn't so obvious that its 1024^2, or that it's even correct.

The same goes for values that are dictated by requirements or standards, that are only used in one place. I find just putting the constant right in place with a comment to the relevant source to be easier to deal with than defining it elsewhere and having to chase both parts down, e.g.:

```<code>// Value must be less than 3.5 volts according to spec blah.
SomeTest = DataSample < 3.50
</code>```

I find better than

```<code>SomeTest = DataSample < SOME_THRESHOLD_VALUE
</code>```

Only when SOME_THRESHOLD_VALUE is used in multiple places does the tradeoff become worth it to define a constant, in my opinion.

Title: Are all magic numbers created the same?

Body:
Not all magic numbers are the same.

I think in that instance, that constant is OK. The problem with magic numbers is when they are magic, i.e. it is unclear what their origin is, why the value is what it is, or whether the value is correct or not.

Hiding 1024 behind BYTES_PER_KBYTE also means you don't see instantly if it is correct or not.

I would expect anyone to know immediately why the value is 1024. On the other hand, if you were converting bytes to megabytes, I would define the constant BYTES_PER_MBYTE or similar because the constant 1,048,576 isn't so obvious that its 1024^2, or that it's even correct.

The same goes for values that are dictated by requirements or standards, that are only used in one place. I find just putting the constant right in place with a comment to the relevant source to be easier to deal with than defining it elsewhere and having to chase both parts down, e.g.:

// Value must be less than 3.5 volts according to spec blah.
SomeTest = DataSample < 3.50

I find better than

SomeTest = DataSample < SOME_THRESHOLD_VALUE

Only when SOME_THRESHOLD_VALUE is used in multiple places does the tradeoff become worth it to define a constant, in my opinion.