问:
If I unite many web apps into one, will I save resources?
I'm comparing 2 different approaches of J2EE application architecture:

Divide independent parts as modules of one big web app.

Divide independent parts as different web apps running on same server.

Between these approaches I prefer the second one because it allows me to make changes without redeploying the whole application. Imagine that you want to change something in app2. In the case of one big app you have to redeploy the whole application. In the second case you have to only redeploy app2.

But I have some doubts about resources consumption such as memory usage and CPU usage. I personally think that each J2EE application, no matter how large it is, has some minimal limit of memory it will necessary use. This minimal limit is what is needed for context loading, web framework config files, jar libs and other things. My hypothesis sounds like "Having many web apps running on same server leads to multiplication of wasting of default minimal resources." Is the picture below correct? Does one big application save me from default resorces overhead multiplication shown on the picture?

答:
I know this question is about apps not services but you might want to read this article as the idea of splitting a service into microservices is not dissimilar to splitting an app into (possibly) micro apps.

Generally many smaller apps/services is the way to go, but ...

"Microservices imply a distributed system. Where before we might have had a method call acting as a subsystem boundary, we now introduce lots of remote procedure calls, REST APIs or messaging to glue components together across different processes and servers."

http://highscalability.com/blog/2014/4/8/microservices-not-a-free-lunch.html

If your separate apps will not need to interact with one another then all is good, but if by splitting up your single app into separate apps you then need to start making API calls to each other then you would encounter extra work and testing.

Another thing to consider are session cookies. With your current "god" app you probably just have one session for all the apps. If by splitting out the apps they truly are separate with their own authentication, session handling and web interface then all is good. But if not then you have some extra work to do.

The issue would then not be about saving resources but more about managing complexity.

Cheers,


问:
Why is there no deterministic object destruction in Java?
I understand and enjoy the benefits of the Garbage Collection in Java. However I don't understand why there is no way in Java to explicitly (and quickly) destroy an object. Surely this could be useful in some cases, I assume performance-critical software.

It's true that in Java the GC will delete an object with no existing reference to it, so if I want an object deleted I can set the reference to it to null. But if I understand correctly, it isn't ensured that the GC will indeed delete the object, at least not immediately. And that's out of the programmer's control.

Why is there no way in Java to explicitly destroy objects?

While I understand that Java was designed to be used as a high-level language, that abstracts away some of the technical details from the programmer to make things easier: Java has become one of the most widely used languages, and is used in huge projects. I assume that in huge projects, performance is often an issue. Since Java had grown to become what it is, why wasn't explicit object destruction added to the language?

答:
Going off of here, which lists the design goals of the Java programming language (emphasis mine):

1.2.2 Robust and Secure

The Java programming language is designed for creating highly reliable software. It provides extensive compile-time checking, followed by a second level of run-time checking. Language features guide programmers towards reliable programming habits.
The memory management model is extremely simple: objects are created with a new operator. There are no explicit programmer-defined pointer data types, no pointer arithmetic, and automatic garbage collection. This simple memory management model eliminates entire classes of programming errors that bedevil C and C++ programmers. You can develop Java code with confidence that the system will find many errors quickly and that major problems won't lay dormant until after your production code has shipped.

The bolded portion, I think, answers your original question pretty well.

As for the second part of your question, I don't think I can personally answer that sufficiently. However, googling led me to this answer by Jon Skeet on Stack Overflow. He mentions that deterministic destructors tend to involve reference counting, which impacts performance and fails for cycles, and refers readers to this email by Brain Harry on resource management. I cannot verify myself whether these answers are true, but they both point towards deterministic destructors not being worth implementing, as their flaws outweighed the potential benefits of implementation.

(By the way, I think that the linked sources would provide too much information to be reasonably quoted here. If I should quote them anyways, let me know)

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


答:
The GC attempts to emulate a world where we never run out of memory, and that's where the advantages in terms of speed and maintainability come from.

In theory, the garbage collector should know more about whether now is a good time to destroy objects than you will while programming it. Often, programs in languages with less abstraction free memory as soon as possible. However, that's not always good for performance. So you might free memory later, where the place that the objects are allocated and destroyed is far removed. This increases the potential that the programmer will miss something. So it can be bad for memory usage, since things should be destroyed when the system gets some breathing room rather than in the middle of a high speed loop. But it can be faster that way.

If the garbage collector is able to run in a separate thread and do its work without corrupting the main thread's memory, then it will be faster than if the main thread handles its memory manually.

In practice, it depends on a lot of different things. Can the process be multithreaded, how much memory is available (less means more collections, more means faster speed), etc. While you can also force garbage collection, that's a very often misused feature. It may clean up those objects, but many times there are references the programmer didn't realize they were still using. So forcibly destroying those objects could create problems that wouldn't become apparent until much later, where the GC knows those objects are still in use.

Combined with recycling, so that the memory for objects doesn't need to be reallocated unless necessary, you can get much faster processing with a lot less work and a lot better maintainability.

Title: Why is there no deterministic object destruction in Java?

Body:
I understand and enjoy the benefits of the Garbage Collection in Java. However I don't understand why there is no way in Java to explicitly (and quickly) destroy an object. Surely this could be useful in some cases, I assume performance-critical software.

It's true that in Java the GC will delete an object with no existing reference to it, so if I want an object deleted I can set the reference to it to null. But if I understand correctly, it isn't ensured that the GC will indeed delete the object, at least not immediately. And that's out of the programmer's control.

Why is there no way in Java to explicitly destroy objects?

While I understand that Java was designed to be used as a high-level language, that abstracts away some of the technical details from the programmer to make things easier: Java has become one of the most widely used languages, and is used in huge projects. I assume that in huge projects, performance is often an issue. Since Java had grown to become what it is, why wasn't explicit object destruction added to the language?


问:
What should happen when code is reached that shouldn't be, according to business or logic rules?
I am currently writing an application that isn't huge but will be used through-out my company of 200+ people and external customers about projects we are working on (not software projects), but there are a fair amount of business rules, along with the implied ones that go with creating, verifying, and maintaining user accounts.

Semi-often I find myself writing code like this

```<code>If (A)
{
   foo();
}
else If (B)
{
   foo2();
}
else
{
   throw new exception("Should not happen because XYZ");
}
</code>```

or

```<code>foo()
{
   //do stuff
   if (D == F)
   {
       throw new exception("Method should not be called if D==F, you forgot how to use this method");
   }
   //do other stuff
}
</code>```

Is this code-smell because it implies that my code might break?

Is this good a programming practice for debugging when things WILL go wrong?

Is this being paranoid?

答:
It all depends on how important not clobbering things when someone makes a mistake, or when SNAFU happens, is. I'm going to assume that's important.

For example, you give an example in foo:

```<code>throw new exception("Method should not be called if D==F, you forgot how to use this method");
</code>```

Assuming that foo doesn't set D and F, and the programmer does, and of course that foo isn't supposed to handle the situation where D and F are equal, it's probably the right choice to throw an error. Programmers are idiots, especially the one who uses your code next.

As for checking that something was successful, that's not a bad idea if you are able to identify possible points of failure. For example, assuming a HTTP grabber that returns a (integer flag, data object) tuple for whatever reason:

```<code>(flag, page_data) = http_fetch(bleh);
if (flag not in ACCEPTABLE_FLAGS) {
    throw new exception("Today is not a good day.");
}
file_thing.write(page_data.bytes);
</code>```

Here, the error checking will mean that nobody knocks down your door because the internet went down and as a result your code clobbered the databases with random junk.

If it's your own work, e.g., that you wrote http_fetch above - do the statements anyway. Unless you're in a really terrible, terrible work environment, people should appreciate that you are just recognising that sometimes the worst case scenario happens.

On the other hand, it's probably excessive to do the following:

```<code>mid = (low + high)/2;
assert((low <= mid) && (mid <= high));
</code>```

In short, if you can identify a point of failure, cover it. Even if it's your own code, sometimes things go wrong and the assumptions you made when writing that code - such as that the caller would actually read the docs - are incorrect.

Body:
It all depends on how important not clobbering things when someone makes a mistake, or when SNAFU happens, is. I'm going to assume that's important.

For example, you give an example in foo:

throw new exception("Method should not be called if D==F, you forgot how to use this method");

Assuming that foo doesn't set D and F, and the programmer does, and of course that foo isn't supposed to handle the situation where D and F are equal, it's probably the right choice to throw an error. Programmers are idiots, especially the one who uses your code next.

As for checking that something was successful, that's not a bad idea if you are able to identify possible points of failure. For example, assuming a HTTP grabber that returns a (integer flag, data object) tuple for whatever reason:

(flag, page_data) = http_fetch(bleh);
if (flag not in ACCEPTABLE_FLAGS) {
    throw new exception("Today is not a good day.");
}
file_thing.write(page_data.bytes);

Here, the error checking will mean that nobody knocks down your door because the internet went down and as a result your code clobbered the databases with random junk.

If it's your own work, e.g., that you wrote http_fetch above - do the statements anyway. Unless you're in a really terrible, terrible work environment, people should appreciate that you are just recognising that sometimes the worst case scenario happens.

On the other hand, it's probably excessive to do the following:

mid = (low + high)/2;
assert((low <= mid) && (mid <= high));

In short, if you can identify a point of failure, cover it. Even if it's your own code, sometimes things go wrong and the assumptions you made when writing that code - such as that the caller would actually read the docs - are incorrect.


答:
I have often pondered the same question.

I was a C++ programmer for many years and an Objective C programmer for many years before that. That experience taught me the discipline to track every object creation and achieve the nirvana of code - to logically assure the ultimate destruction of every created object and buffer.

And what a discipline it was - I could guarantee that I never leaked memory anywhere in my code. But memory leaked! Any library I used was a chink in this armor. Threading was a nightmare!! The discipline was valuable but it just did not solve the problem. Even the most carefully written code would require a restart after a few weeks of continuous running and many apps could not run stably for more than about 24 hours.

The solution is Garbage Collection. It makes everything so easy - you just let go of the memory and it floats off like a Helium-filled balloon to be gathered and recycled.

There are two primary benefits that make it a winner:

It is simple - just let go of the object.

The GC process also compacts your heap.

Now those two alone creates an order of magnitude improvement in the stability of your code and the ease of writing and debugging. The only downside is you have to suffer the indignity of occasionally putting up with the inevitable delay of the GC.

A quick consideration of allowing a mixture of immediate and postponed discard also proves pointless.

Say you have a Map tha you have filled with some data and now you know without a doubt that it will not be needed again. Surely manually freeing it would save you peanuts - just the nodes, not the keys or the values. A tiny gain of some fragmented values.

Bottom line - it's so simple even an incompetent programmer can write leak-free code.


问:
How faster could a dedicated chip do sequential squaring modulo operations to break a time crypto capsule?
I'm facing a very real problem and, sadly, I cannot find the answer on my own: I'm hitting my limit as a programmer because my hardware knowledge is not sufficiently advanced at all.

It's an issue I'm encountering during the development of the system (I need to find safe parameters value which depends on the answer to the question I'm asking here) (maybe crypto.SE would be better but crypto.SE seems more about theoretical questions about math/cryptography).

For a project I'm working on I need to use a "time capsule cryptosystem". More specifically the following one, invented by Rivest (the 'R' in 'RSA'):

Rivest's time capsule crypto puzzle

It is an inherently sequential operation: parallelization here is of no use. An attacker could use a botnet of million computers: it wouldn't help. One million ASIC chips wouldn't help either. The solution can only be found sequentially, by design.

Now I need to approximate (one or two orders of magnitude off is ok: an approximation 10x faster/slower or even 100x faster/slower ain't really an issue) how much faster could a dedicated chip solve that puzzle compared to a fast CPU (a fast core, really).

Basically solving that puzzle consists in doing a lot of squarings modulo n. Let's consider there's no "attack" on that puzzle: I've chosen bit enough RSA integers etc.

Would a GPU help compared to a CPU here? A FPGA? Would a dedicated chip like some ASIC chip help?

If any of these would help, how can I determine how much faster it could be than  a fast CPU?

I'd need some back-of-the-envelope calculation and, as I stated previously, an approximation about 10x or 100x the actual answer ain't that a big problem.

I guess my question boils down to something like (but feel free to rewrite if I'm mistaken): knowing that the problem is inherently sequential and consists in repeated squaring modulo n operation, can you build/program some hardware to only do sequential squaring modulo operations and how much faster would it be than an actual CPU?

答:
CPU:

The problem really does depend on the speed of the CPU. We already have diverged from the ballpark range presented in the article, as in 2012 we did not have commercially available 10GHz CPUs. In this case, it would be rather difficult because we're dealing with several factors:

CPU speed

L1 and L2 cache size

Bus speed

Algorithm optimization

Available CPU architecture

Memory speed

Cache misses

So I'm going to stick with the "35 year algorithm" based off their original prediction.

GPU:

A GPU isn't going to help in this case. These devices are all about paraellelization and aren't going to help with this kind of algorithm.

FPGA/ASIC:

In this scenario, it's entirely possible to design an FPGA/ASIC that would do an entire operation in one tick. Since we don't care about the actual division result, and only care about the result mod N, we could theoretically make this fairly fast. However it's extremely difficult to estimate the exact speed we could achieve. This would be based off many factors:

The algorithm we use.

The size/speed of the components.

The actual hardware components used.

The quality of the components used.

The build process used.

If we could estimate that our FPGA/ASIC would run at 1 MHz, which would complete the problem in ~2.53 years.

On another hand, if we could somehow develop and FPGA/ASIC that would run at 1 GHz, then we would complete the problem in ~22 hours.


答:
If you are handling the case where you don't expect something to ever happen, then this is one perfect reason to use runtime exceptions. Also, from http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html (if you are using Java, that is), runtime exceptions should be used when the client cannot do anything to work around the issue (as probably is the case you described). If the case you've shown occurs, it represents a code bug, which is when runtime exceptions should be thrown.

However, you should probably only do this in few unique or special cases, not in every single method in the system--that would be being paranoid and not trusting your code.

Title: What should happen when code is reached that shouldn't be, according to business or logic rules?

Body:
I am currently writing an application that isn't huge but will be used through-out my company of 200+ people and external customers about projects we are working on (not software projects), but there are a fair amount of business rules, along with the implied ones that go with creating, verifying, and maintaining user accounts.

Semi-often I find myself writing code like this

```<code>If (A)
{
   foo();
}
else If (B)
{
   foo2();
}
else
{
   throw new exception("Should not happen because XYZ");
}
</code>```

or

```<code>foo()
{
   //do stuff
   if (D == F)
   {
       throw new exception("Method should not be called if D==F, you forgot how to use this method");
   }
   //do other stuff
}
</code>```

Is this code-smell because it implies that my code might break?

Is this good a programming practice for debugging when things WILL go wrong?

Is this being paranoid?


问:
Dealing with not knowing parameter names of a function when you're calling it
Here's a programming/language problem I'd like to hear your thoughts on.

We have developed conventions that most programmers (should) follow that aren't a part of the languages syntax but serve to make code more readable. These are of course always a matter of debate but there's at least some core concepts that most programmers find agreeable. Naming your variables appropriately, naming in general, making your lines not outrageously long, avoiding long functions, encapsulations, those things.

However, there's a problem that I have yet to find anyone commenting on and that just might be the biggest one of the bunch. It's the problem of arguments being anonymous when you call a function.

Functions stem from mathematics where f(x) has a clear meaning because a function has a much more rigorous definition that it usually does in programming. Pure functions in mathematics can do a lot less than they can in programming and they are a much more elegant tool, they usually only take one argument (which is usually a number) and they always return one value (also usually a number). If a function takes multiple arguments, they are almost always just extra dimensions of the function's domain. In other words, one argument isn't more important than the others. They are explicitly ordered, sure, but other than that, they have no semantic ordering.

In programming however, we have more freedom defining functions, and in this case I'd argue it isn't a good thing. A common situation, you have a function defined like this

```<code>func DrawRectangleClipped (rectToDraw, fillColor, clippingRect) {}
</code>```

Looking at the definition, if the function is written correctly, its perfectly clear what's what. When calling the function, you might even have some intellisense/code completion magic going on in your IDE/editor that will tell you what the next argument should be. But wait. If I need that when I'm actually writing the call, isn't there something we're missing here? The person reading the code doesn't have the benefit of an IDE and unless they jump to the definition, they have no idea which of the two rectangles passed as arguments is used for what.

The problem goes even further than that. If our arguments come from some local variable, there might be situations where we don't even know what the second argument is since we only see the variable name. Take for example this line of code

```<code>DrawRectangleClipped(deserializedArray[0], deserializedArray[1], deserializedArray[2])
</code>```

This is alleviated to various extents in different languages but even in strictly typed languages and even if you name your variables sensibly, you don't even mention the type the variable is when you're passing it to the function.

As it usually is with programming, there are a lot of potential solutions to this problem. Many are already implemented in popular languages. Named parameters in C# for example. However, all that I know have significant drawbacks. Naming every parameter on every function call can't possibly lead to readable code. It almost feels like maybe we're outgrowing possibilities that plain text programming gives us. We've moved from JUST text in almost every area, yet we still code the same. More information is needed to be displayed in the code? Add more text.
Anyways, this is getting a bit tangential so I'll stop here.

One reply I got to the second code snippet is that you would probably first unpack the array to some named variables and then use those but the variable's name can mean many things and the way it's called doesn't necessarily tell you the way it's supposed to be interpreted in the context of the called function.
In the local scope, you might have two rectangles named leftRectangle and rightRectangle because that's what they semantically represent, but it doesn't need to extend to what they represent when given to a function.

In fact, if your variables are named in the context of the called function than you're introducing less information than you potentially could with that function call and on some level if does lead to code worse code. If you have a procedure that results in a rectangle you store in rectForClipping and then another procedure that provides rectForDrawing, then the actual call to DrawRectangleClipped is just ceremony. A line that means nothing new and is there just so the computer knows what exactly you want even though you've explained it already with your naming. This isn't a good thing.

I'd really love to hear fresh perspectives on this. I'm sure I'm not the first one to consider this a problem, so how is it solved?

答:
You should use objective-C then, here is a function definition:

```<code>- (id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject
</code>```

And here it is used:

```<code>[someObject performSelector:someSelector withObject:someObject2 withObject:someObject3];
</code>```

I think ruby has similar constructs and you can simulate them in other languages with key-value-lists.

For complex functions in Java I like to define dummy variables in the functions wording. For your left-right-example:

```<code>Rectangle referenceRectangle = leftRectangle;
Rectangle targetRectangle = rightRectangle;
doSomeWeirdStuffWithRectangles(referenceRectangle, targetRectangle);
</code>```

Looks like more coding, but you can for example use leftRectangle and then refactor the code later with "Extract local variable" if you think it will not be understandable to a future maintainer of the code, which might or might not be you.

Body:
You should use objective-C then, here is a function definition:

- (id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject

And here it is used:

[someObject performSelector:someSelector withObject:someObject2 withObject:someObject3];

I think ruby has similar constructs and you can simulate them in other languages with key-value-lists.

For complex functions in Java I like to define dummy variables in the functions wording. For your left-right-example:

Rectangle referenceRectangle = leftRectangle;
Rectangle targetRectangle = rightRectangle;
doSomeWeirdStuffWithRectangles(referenceRectangle, targetRectangle);

Looks like more coding, but you can for example use leftRectangle and then refactor the code later with "Extract local variable" if you think it will not be understandable to a future maintainer of the code, which might or might not be you.


问:
In voice recognition programs, what methods are generally used to separate voice from noise?
I think voice recognition is cool, and I might start studying it soon, but one big question that I've always wondered about is "How do the programmers separate the noise from the voice?"

I mean, if you've watched "Her", you'll notice the main character uses voice commands commonly in quiet places, but today, voice recognition is mostly used in the car, amid a LOT of background noise, and even possibly background voices.

I've used Siri in these loud situations, and I'm always impressed that the program still understands me over the noise.

So, without going into detailed specifics, I'd like to know what methods or concepts are generally used by programmers to do this.

答:
This is a big question, but the algorithms fall broadly under the category of signal processing.

In short, there are a couple of things that make a voice stand out (or any other sound, for that matter, though I will call every sound a voice for simplicity's sake). They are pitch, timbre, and loudness.

Pitch is probably the most familiar, but specifically it refers to the frequencies occupied by a voice. Most people voices have a uniform pitch, which is to say I've never heard of a single person singing a chord.

Timbre is what makes the difference between a saxaphone and a violin playing the same note. It's like the flavor of the sound, and can be affected by the acoustics of the room, the noise (is it breathy or raspy), resonance, etc.

Loudness is like the average pressure of the air's movement. It's surprisingly complicated, but for my explanation a volume knob works.

Okay? Now, to isolate a sound, we can try and trace these three factors. It's pretty rare for a voice to change pitch, timbre, and loudness simultaneously. So we'll call a dramatic change in two of these a different voice.

A fourier transform of your audio signal can give you a "frequency-loudness over time" view of it. So, if you look at a fourier transform (the graph at the bottom of the following image)

you can begin to get an idea of how this can be carried out. Once you know where a voice lies along the spectrum in time, you can apply a moving band pass filter to it to isolate that signal.

Still, this is something that has taken a long time for people to get right. Siri is just the latest in a long line of voice recognition applications of varying ability.


问:
Are short identifiers bad?
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf

答:
My thinking is that they are not bad in themselves but they are uninformative unless they are very standard.

So loop variables being i, j and k is so standard that there is no reason not to use them if you are creating an indexed loop.

The other place I will use a very short identifier is when I'm declaring a temporary variable that will go out of scope in a few lines time- the temporary variable from a foreach loop, for example. If it's not going to be referred to anywhere else then it's easy for anyone reading the code to see the declaration and follow what it is being used for. If it's going to be used for more than five or six lines, though, I'll be looking to give it a clearer name.

Beyond that I try to use informative length identifiers- particularly at a class level I want an identifier that you can read and get an idea of what the variable is for. If they are getting too long ( and I do see code sometimes with four or five words strung together for an identifier ) I tend to regard that as a code smell - if I need that much text to distinguish my variables are they actually a group that could be better stored in a hashmap or list? Could I be creating some kind of object to model this data more accurately? Sometimes you can't but a very long identifier is an indicator that there is something worth looking at here.

Title: Are short identifiers bad?

ContentLicense: CC BY-SA 2.5


问:
Origins of code indentation
I am interested in finding out who introduced code indentation, as well as when and where it was introduced.

It seems so critical to code comprehension, but it was not universal. Most Fortran and Basic code was (is?) unindented, and the same goes for Cobol.

I am pretty sure I have even seen old Lisp code written as continuous, line-wrapped text. You had to count brackets in your head just to parse it, never mind understanding it.

So where did such a huge improvement come from? I have never seen any mention of its origin.

Apart from original examples of its use, I am also looking for original discussions of indentation.

答:
The origins of indented code probably can be found in ALGOL:

ALGOL introduced code blocks and the begin and end pairs for delimiting them and it was also the first language implementing nested function definitions with lexical scope.

Title: Origins of code indentation


问:
Creating objects with user-defined variable names
Context:

I am making a learning project in XNA. What I would like to be able to do is allow the game to be moddable by allowing the users to place arbitrary values into a JSON data file which is read into the game. The thing is that I want to avoid hardcoding if possible and have it automagically work for whatever the user throws at the engine.

Problem:

I have no idea how to design class(es) that can accommodate this sort of behavior, as my understanding is that whatever loads the JSON has to map it to existing variables on the object:

```<code>public class SomeGameEntity
{
    public float Strength { get; set; }
    public bool IsStrong { get; set; }
}
</code>```

But what I want is for the client code to be able to do something like:

```<code>SomeGameEntity.Stats["Strength"] = 16;
SomeGameEntity.Stats["IsStrong"] = true;
</code>```

My Solution:

Upon consideration, I would only define a few valid data types, likely float, bool, and string (other types, such as XNA.Color, would probably have to be inferred from a combination of RGB floats on the object.)

Thus, what makes sense is to create a class such as the following:

```<code>public class EntityStatComponent
{
    private readonly Dictionary<string, float> _floatValues;
    private readonly Dictionary<string, string> _stringValues;
    private readonly Dictionary<string, bool> _boolValues;

    public float GetValue(string name) { }
    public void SetValue(string name, float value) { }

    public string GetString(string name) { }
    public void SetString(string name, string value) { }

    public bool GetFlag(string name) { }
    public void SetFlag(string name, bool value) { }
}
</code>```

But, this seems like a heavy-handed approach, especially with three dictionaries per active object. I would probably say there are less than 250 objects onscreen at a time (characters, projectiles, etc).

Unfortunately, I don't think generic typing is the way to go for this, since for T, it would have to accept a single data type into the dictionary. Alternatively, if I allowed any T value to be used via the get/set method, I would have to use the if(someArg is float) stuff, which I understand to be frowned upon.

Am I overlooking something, or is there a better way to do it?

答:
Loading values from JSON is only useful if at some point something uses these values. Since you want to allow modders to use "arbitrary" structures(which I assume means "their own structures"), it's clear that it's not your own code that will use the data from that JSON - it'll be the modders code.

Now, there are two ways for letting modders add their code to your game - dynamic module loading and embedded scripting language.

If you use dynamic module loading - which means the modders write C# code with an API you supply, compile it to DLL, and your game loads that DLL - you should use hard coded classes to represent the data structure. However, you will not be the one who defines these classes - the modders will define them in their modules and send them as generic parameters to your JSON loading method(which should use generic reflection to delegate it to a JSON library). That way you won't be imposing the structure on the modders, but they'll still be able to use a well defined static-typed structure.

If you use an embedded scripting language(like LUA or JavaScript), you should just use a string->object map. Yes, I know that string->object maps are considered a code smell in static-typed languages, but scripting languages are usually dynamic-typed. You are going to loose all static structure anyways when you pass the data to the scripting language, and you are not going to access it from C#, so why not save yourself the trouble and ditch that structure(only for the values from the JSON, of course) from the beginning?


答:
We have to decouple two concepts here.

As of Java 7, the language does have RAII. It's called the try-with-resources statement.

```<code>static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}
</code>```

This guarantees that the reader will be closed no matter how the block exits.

Even without using try-with-resources, you can deterministically close a stream by calling br.close() when you want.

What's not deterministic is deleting the object from memory. That has to wait until there are no more references to the object and the garbage collector notices that. Trying to make that deterministic depends on potentially a lot of the program (e.g. does a listener, the debugger, or a logger still reference the object?) and the garbage collector's operational details (which GC algorithm is in use? is it a concurrent collector? which generation is the object in? how urgent is collection needed right now? ...).

Body:
We have to decouple two concepts here.

As of Java 7, the language does have RAII. It's called the try-with-resources statement.

static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}

This guarantees that the reader will be closed no matter how the block exits.

Even without using try-with-resources, you can deterministically close a stream by calling br.close() when you want.

What's not deterministic is deleting the object from memory. That has to wait until there are no more references to the object and the garbage collector notices that. Trying to make that deterministic depends on potentially a lot of the program (e.g. does a listener, the debugger, or a logger still reference the object?) and the garbage collector's operational details (which GC algorithm is in use? is it a concurrent collector? which generation is the object in? how urgent is collection needed right now? ...).


问:
How significant is node's advantage of training developers in only one language and putting them on tasks across the tech-stack?
I have recently joined a startup as CTO/co-founder. The startup and I have been thinking about moving the existing codebase (which is in PHP5.5, laravel framework) to node.js .

Main reason for this being that at the stage we are in right now, I'll need to hire talented, but inexperienced developers and train them to work on different parts of the project. JS is already being used in a very big angular app, and will also be used in the mobile app (we are planning to go the phone gap route). The api only exists in PHP.

I personally can re-implement the existing api in node.js in 3-6 weeks optimistically (I am confident of that time because I myself built the laravel api backend) and have a pretty good idea of the feature set required. Also, that's a time that the startup can afford at this stage.

I think that having one language across our tech stack can increase our ability to get the maximum out of new developers who join the company as we can train them only in JS and in use their skills across the tech stack, by giving them proper training before exposing them to a new area of the stack.

My question is, what are the benefits of training inexperienced devs in a single technology stack?  Are my assumptions correct based on this list of benefits?  Does an affordable 3-6 week turnaround become more realistic if inexperienced devs can focus on a single technology stack?

答:
There are several possibly wildly overoptimistic assumptions in your idea.  I'm going to focus on two of them.

Technology rewrite in 3 weeks

I'm going to work off of the Cocomo II model, change every driver to be in your favor, and poke at numbers and say you have about 1000 SLC give or take (its an estimate based on you are doing all, being an expert in all the technologies used, and skipping the phases other than 'construction' and pushing yourself).  If you have more than 1000 SLC, you might want to reconsider that number of 3 weeks.

1000 modified, 100% code modified, 0% design modified, 0% integration required...

You are switching technologies, frameworks, and even the language model.  This is not a small change.  You could be off by several factors or even an order of magnitude.  Before going too far down the road with your "3 weeks", I would suggest getting a copy of Software Estimation: Demystifying the Black Art  by Steve McConnell and make sure you are confident with your estimation.

One language across the stack

Yea, it may be one language across the stack.  But programing for a mobile device vs a web page vs a back end are completely different ways of writing code.  There are things that mobile developers think about (connectivity, different devices, different browsers) that backend don't concern themselves with because they are a given.

While you may be writing one language across the stack, its as different as writing Java ME vs Java SE vs Java EE.  They all use Java, they all have the same base libraries, but a Java ME person will never even think of Spring or Hibernate and a Java EE type will not worry about Swing or Java FX.

The ideal of one technology across the stack does exist, but do not pretend that you can take a JavaScript UI type and be able to swap them into the position of a Node.js with no ramp up time for that new technology stack.

Yes, one language across the stack is a nice ideal.  And something you might want to work for.  But doing what appears to be a rush job to make it so will not make for a good platform or be of long term benefit.  It also forces you into using one language across the entire set of applications when other languages may be a better fit (but you can't change it because you are a pure javascript shop).


问:
How long does a Comp Sci degree last?
I keep hearing from people that if I don't become a programmer soon after graduation my degree will be a useless piece of paper, they claim it will become outdated.  I kind of find this hard to believe considering what I was taught at a fairly good school has been standard practice for some time.

So is this a true belief in industry?  That somehow I become less desirable after a year or two, even though the graduates who comes after me pretty much get the same identical education.

答:
Separation of theory & Practice:

In my mind, I think theory will be always relevant for example a linked list will always be.

The practical aspect (in terms of specific technologies) will naturally decay as soon as newer technologies replace them.

Title: How long does a Comp Sci degree last?


问:
Is this actually good OO design?

Context

I have Specification class with several properties including: StartDate, EndDate, DaysToComplete, DateToComplete.

A specification contains a list of required courses (i.e. a company requires employees to take training... perhaps a technical, diversity, or an ethics class). Based on a specification, courses will be mandated to employees.

Validation Concerns

StartDate and EndDate refer to the window of time in which a company can mandate a class to a user. DaysToComplete is how many days the employee has to compete training from the time it's mandated to them, whereas DateToComplete is the last day they have to complete the course.

StartDate must always be specified

DaysToComplete and DateToComplete are mutually exclusive... one and only one must be specified.

If EndDate is not specified, then DaysToComplete must be used

If StartDate = EndDate, then DateToComplete must be used

And there are other obvious validation rules such as the fact that you wouldn't have an EndDate greater than the DateToComplete since you wouldn't mandate a course after it already had to be completed.

The Problem

It seems as though there is a case here for having a base class and 4 derived classes with the following properties (i.e. this is how I was instructed to and did design the objects):

SpecificationBase: StartDate

PerpetualSpecification: DaysToComplete

OneTimeSpecification*: DateToComplete

FixedSpecification: EndDate, CompletionDate

SlidingSpecification: EndDate, DaysToComplete

*When a user enters an EndDate that equals the StartDate they must use DateToComplete. In this case the EndDate is not actually saved though.

So we're using inheritance to do two things here: encapsulate validation rules and not expose properties that don't exist for particular scenarios.

As far as validation goes, from my perspective, the rules are always the same for all scenarios. Yes, certain properties don't apply in all scenarios but for the ones that do the validation logic really doesn't change. The argument, however, is that it is easier to comprehend the validation logic this way because putting it in all in the base class would be too complicated (writing a factory method to choose the right type based on user input and create it with reflection was, by comparison, considered not a big deal at all).

And as for hiding unused properties (or as my team lead insists: not exposing properties that don't exist), the argument started out as being an OO design principle that data and behavior should be coupled... until I pointed out that it would still be coupled in the base class without the derived classes (not to mention the data isn't decoupled in the database either).

I highly respect my team lead and from a purely philosophical/idealistic point of view this design seems great, but in practice it seems to create more problems than it solves:

Had to create a factory method since we just get input from users without making them specify the type

3rd party tools that rely on reflection can't work with a list of different types with different properties so I have to create a proxy (or cheat and just put the data into an anonymous type and hope I'm never asked to provide a way to update the data from a grid control)

Because consuming code only uses the factory method, it doesn't know what specific type it has or which properties are on it. This means if/then statements to test for what type I'm working with before trying to access a property that might not exist.

I'm sorry for the incredibly long essay, but I just wanted to provide ample context and background before asking my question: Is this 'really' good OO design? I feel like good OO design should make life easier... not harder. What am I missing here?

Edit: More Info

I realize now I left out a an important detail. My team lead is very, very big on requiring all data needed to initialize a proper type to be passed into its constructor (and not allowing a default constructor), and putting validation logic in the properties' set accessors. He feels this is the best way to prevent bad data from getting into the database. I don't particularly like this approach, however he's worked at some places where lack of good validation caused serious, serious problems.

So that's why I use a factory method... but the drawback of that is that type casting is required when the extended properties have to be worked with. Another drawback is that if I make the properties virtual then now, because of our validation approach, I have to call virtual properties from the constructor. Actually I ended up doing just that of necessity and practicality, but I'm didn't mention it in the beginning because doing so was a 'work around' to the actual design that I wanted to ask about.

答:
Because consuming code only uses the factory method, it doesn't know
  what specific type it has or which properties are on it. This means
  if/then statements to test for what type I'm working with before
  trying to access a property that might not exist.

Now that's a code smell no doubt.

It's breaking encapsulation and not making proper use of polymorphism.

Whatever logic expressed by this switching on type, it should be contained in the class. Implementation details are not something your calling code should be concerned about.

Let's say that your calling code wants to know what's the actual last day (or end date) of the specification object. It's not interested how it's calculated or derived.

Based on your summary, I imagine your current implementation looks similar to this:

```<code>DateTime actualEndDate;
if (specification is PerpetualSpecification)
{
    // I ommit casting, don't use DateTime.Add etc. for clarity
    actualEndDate = specification.StartDate + specification.DaysToComplete;
}
else if (specification is OneTimeSpecification)
{
    actualEndDate = specification.DateToComplete;
}
else if (specification is FixedSpecification)
{
    actualEndDate = specification.EndDate != null
        ? specification.EndDate
        : specification.StartDate + specification.DaysToComplete;
}
// etc.
</code>```

So it has to know a lot about how all these classes work internally. It's none of its business really. Plus, it introduces redundancy. It violates important design principles such as DRY as well as Single Source of Truth (if you need to compute actualEndDate in more than one place, these independent implementations are likely to become inconsistent over time).

If all the calling code wants to know is when comes the actual last day, implement it in your classes:

```<code>public abstract class SpecificationBase
{
    public abstract DateTime ActualLastDay
    {
        get;
    }

    // ...
}
</code>```

And then:

```<code>public class FixedSpecification : SpecificationBase
{
    public override DateTime ActualLastDay
    {
        get
        {
            return EndDate ?? StartDate + specification.DaysToComplete;
        }
        // writing a setter that deals with specific requirements
        // of this particular class could also be possible actually
    }

    // ...
}
</code>```

After that make your calling code just query specification for ActualLastDay property instead of if-elsing through all possible types.

Now it's no longer a problem that some properties only exist in some child classes.

You're creating a facade that will shield you from this.

(I can't rule out that I'm misunderstanding the question somehow - if my answer is off, some examples on your part would be appreciated)

Title: Is this actually good OO design?

Body:
Because consuming code only uses the factory method, it doesn't know
  what specific type it has or which properties are on it. This means
  if/then statements to test for what type I'm working with before
  trying to access a property that might not exist.

Now that's a code smell no doubt.

It's breaking encapsulation and not making proper use of polymorphism.

Whatever logic expressed by this switching on type, it should be contained in the class. Implementation details are not something your calling code should be concerned about.

Let's say that your calling code wants to know what's the actual last day (or end date) of the specification object. It's not interested how it's calculated or derived.

Based on your summary, I imagine your current implementation looks similar to this:

DateTime actualEndDate;
if (specification is PerpetualSpecification)
{
    // I ommit casting, don't use DateTime.Add etc. for clarity
    actualEndDate = specification.StartDate + specification.DaysToComplete;
}
else if (specification is OneTimeSpecification)
{
    actualEndDate = specification.DateToComplete;
}
else if (specification is FixedSpecification)
{
    actualEndDate = specification.EndDate != null
        ? specification.EndDate
        : specification.StartDate + specification.DaysToComplete;
}
// etc.

So it has to know a lot about how all these classes work internally. It's none of its business really. Plus, it introduces redundancy. It violates important design principles such as DRY as well as Single Source of Truth (if you need to compute actualEndDate in more than one place, these independent implementations are likely to become inconsistent over time).

If all the calling code wants to know is when comes the actual last day, implement it in your classes:

public abstract class SpecificationBase
{
    public abstract DateTime ActualLastDay
    {
        get;
    }

    // ...
}

And then:

public class FixedSpecification : SpecificationBase
{
    public override DateTime ActualLastDay
    {
        get
        {
            return EndDate ?? StartDate + specification.DaysToComplete;
        }
        // writing a setter that deals with specific requirements
        // of this particular class could also be possible actually
    }

    // ...
}

After that make your calling code just query specification for ActualLastDay property instead of if-elsing through all possible types.

Now it's no longer a problem that some properties only exist in some child classes.

You're creating a facade that will shield you from this.

(I can't rule out that I'm misunderstanding the question somehow - if my answer is off, some examples on your part would be appreciated)


问:
How to compute scrum burndown chart when projects overlap?
In my team we have a multiple projects, some short term and some long term. The team is required to deliver these projects on different dates and the effort to deliver these is run in parallel with the team working on stories for more than one project during each sprint.

When trying to compute our burndown we aren't sure what to do.

As the team is split between projects the velocity can change dramatically week-on-week as people shuffle to the tasks best suited for their specialty across the projects. This makes it difficult to create a reliable and meaningful burndown chart for each project.

However if we combine the stories into a single burndown chart how can we track against the release if the release dates are different and it isn't obvious which points remain for each project.

Is there a good method for dealing with this?

答:
Burndown charts are used to estimate the amount of effort(points) remaining for a release. Sometimes, this can be projected to get a rough approximation of the release date based on delivery.

If your goal is to purely to track story points (not release date), then most tools allow you to create features or sub-groups within a master project, and then get story point charts for each feature separately. This helps you keep track of the flow of stories in each feature.

However, if you are trying to track on-time delivery against a release date, your workflow renders it somewhat meaningless. Consider, your team puts in a different number of hours every week for any particular project. If you do not know how much effort you can put in for each week in the future, how will you even calculate when all the tasks will end?

That said, I do have a few suggestions. You can try to "approximate" a standard velocity for each individual project. Actively change your team's prioritization so that the team "as a whole" outputs some standard velocity per project. Individuals would still vary as per their expertise in specific projects.

You would be doing this anyway to make sure that no project falls behind. Just formalize that process and then use this velocity to track your on-time metrics.


问:
Correct way to inject dependencies in Business logic service?
Currently the structure of my application is as below
Web App --> WCF Service (just a facade) --> Business Logic Services --> Repository -> Entity Framework Datacontext

Now each of my Business logic service is dependent on more than 5 repositories ( I have interfaces defined for all the repos) and I am doing a Constructor injection right now(poor mans DI instead of using a proper IOC as it was determined that it would be a overkill for our project). Repositories have references to EF datacontexts. Now some of the methods in the Business logic service require only one of the 5 repositories, so If I need to call that method I would end up instantiating a Service which will instatiate all 5 repositories which is a waste. An example:

```<code>public class SomeService : ISomeService
{
   public(IFirstRepository repo1, ISecondRepository repo2, IThirdRepository repo3)
   {}

   // My DoSomething method depends only on repo1 and doesn't use repo2 and repo3
   public DoSomething()
   {
        //uses repo1 to do some stuff, doesn't use repo2 and repo3
   }

   public DoSomething2()
   {
     //uses repo2 and repo3 to do something, doesn't require repo1
   }

   public DoSomething3()
   {
     //uses repo3 to do something, doesn't require repo1 and repo2
   }
}
</code>```

Now if my I have to use DoSomething method on SomeService I end up creating both IFirstRepository,ISecondRepository and IThirdRepository but using only IFirstRepository, now this is bugging me, I can seem to accept that I am un-necessarily creating repositories and not using them.

Is this a correct design? Are there any better alternatives? Should I be looking at Lazy instantiation Lazy<T> ?

答:
I would pull each method of the service out into a Command, then use a DI container to instantiate the correct command with the correct parameters. By pulling each method into a command you no longer force separate commands to take on shared dependencies.

In practice your poor man's DI might look like:

```<code>public delegate T Factory<T>;

public class SomeService : ISomeService
{
   public(Factory<IFirstRepository> repo1Factory, /* ... */)
   {}

   // My DoSomething method depends only on repo1 and doesn't use repo2 and repo3
   public DoSomething()
   {
        //uses repo1 to do some stuff, doesn't use repo2 and repo3
       var handler = new DoSomethingHandler(repo1Factory());
       handler.Execute();
   }

}
</code>```

Body:
I would pull each method of the service out into a Command, then use a DI container to instantiate the correct command with the correct parameters. By pulling each method into a command you no longer force separate commands to take on shared dependencies.

In practice your poor man's DI might look like:

public delegate T Factory<T>;

public class SomeService : ISomeService
{
   public(Factory<IFirstRepository> repo1Factory, /* ... */)
   {}

   // My DoSomething method depends only on repo1 and doesn't use repo2 and repo3
   public DoSomething()
   {
        //uses repo1 to do some stuff, doesn't use repo2 and repo3
       var handler = new DoSomethingHandler(repo1Factory());
       handler.Execute();
   }

}


答:
In Javascript (or ECMAScript), for example, many programmers grew accustomed to

passing parameters as a set of named object properties in a single anonymous object.

And as a programming practice it got from programmers to their libraries and from there to other programmers who grew to like it and use it and write some more libraries etc.

Example

Instead of calling

```<code>function drawRectangleClipped (rectToDraw, fillColor, clippingRect)
</code>```

like this:

```<code>drawRectangleClipped(deserializedArray[0], deserializedArray[1], deserializedArray[2])
</code>```

, which is a valid and correct style, you call the

```<code>function drawRectangleClipped (params)
</code>```

like this:

```<code>drawRectangleClipped({
    rectToDraw: deserializedArray[0],
    fillColor: deserializedArray[1],
    clippingRect: deserializedArray[2]
})
</code>```

, which is valid and correct and nice with regard to your question.

Off course, there have to be suitable conditions for this - in Javascript this is much more viable than in, say, C. In javascript, this even gave birth to now widely used structural notation that grew popular as a lighter counterpart to XML. It's called JSON (you may have already heard about it).

Title: Dealing with not knowing parameter names of a function when you're calling it

Body:
Here's a programming/language problem I'd like to hear your thoughts on.

We have developed conventions that most programmers (should) follow that aren't a part of the languages syntax but serve to make code more readable. These are of course always a matter of debate but there's at least some core concepts that most programmers find agreeable. Naming your variables appropriately, naming in general, making your lines not outrageously long, avoiding long functions, encapsulations, those things.

However, there's a problem that I have yet to find anyone commenting on and that just might be the biggest one of the bunch. It's the problem of arguments being anonymous when you call a function.

Functions stem from mathematics where f(x) has a clear meaning because a function has a much more rigorous definition that it usually does in programming. Pure functions in mathematics can do a lot less than they can in programming and they are a much more elegant tool, they usually only take one argument (which is usually a number) and they always return one value (also usually a number). If a function takes multiple arguments, they are almost always just extra dimensions of the function's domain. In other words, one argument isn't more important than the others. They are explicitly ordered, sure, but other than that, they have no semantic ordering.

In programming however, we have more freedom defining functions, and in this case I'd argue it isn't a good thing. A common situation, you have a function defined like this

```<code>func DrawRectangleClipped (rectToDraw, fillColor, clippingRect) {}
</code>```

Looking at the definition, if the function is written correctly, its perfectly clear what's what. When calling the function, you might even have some intellisense/code completion magic going on in your IDE/editor that will tell you what the next argument should be. But wait. If I need that when I'm actually writing the call, isn't there something we're missing here? The person reading the code doesn't have the benefit of an IDE and unless they jump to the definition, they have no idea which of the two rectangles passed as arguments is used for what.

The problem goes even further than that. If our arguments come from some local variable, there might be situations where we don't even know what the second argument is since we only see the variable name. Take for example this line of code

```<code>DrawRectangleClipped(deserializedArray[0], deserializedArray[1], deserializedArray[2])
</code>```

This is alleviated to various extents in different languages but even in strictly typed languages and even if you name your variables sensibly, you don't even mention the type the variable is when you're passing it to the function.

As it usually is with programming, there are a lot of potential solutions to this problem. Many are already implemented in popular languages. Named parameters in C# for example. However, all that I know have significant drawbacks. Naming every parameter on every function call can't possibly lead to readable code. It almost feels like maybe we're outgrowing possibilities that plain text programming gives us. We've moved from JUST text in almost every area, yet we still code the same. More information is needed to be displayed in the code? Add more text.
Anyways, this is getting a bit tangential so I'll stop here.

One reply I got to the second code snippet is that you would probably first unpack the array to some named variables and then use those but the variable's name can mean many things and the way it's called doesn't necessarily tell you the way it's supposed to be interpreted in the context of the called function.
In the local scope, you might have two rectangles named leftRectangle and rightRectangle because that's what they semantically represent, but it doesn't need to extend to what they represent when given to a function.

In fact, if your variables are named in the context of the called function than you're introducing less information than you potentially could with that function call and on some level if does lead to code worse code. If you have a procedure that results in a rectangle you store in rectForClipping and then another procedure that provides rectForDrawing, then the actual call to DrawRectangleClipped is just ceremony. A line that means nothing new and is there just so the computer knows what exactly you want even though you've explained it already with your naming. This isn't a good thing.

I'd really love to hear fresh perspectives on this. I'm sure I'm not the first one to consider this a problem, so how is it solved?

Body:
In Javascript (or ECMAScript), for example, many programmers grew accustomed to

passing parameters as a set of named object properties in a single anonymous object.

And as a programming practice it got from programmers to their libraries and from there to other programmers who grew to like it and use it and write some more libraries etc.

Example

Instead of calling

function drawRectangleClipped (rectToDraw, fillColor, clippingRect)

like this:

drawRectangleClipped(deserializedArray[0], deserializedArray[1], deserializedArray[2])

, which is a valid and correct style, you call the

function drawRectangleClipped (params)

like this:

drawRectangleClipped({
    rectToDraw: deserializedArray[0],
    fillColor: deserializedArray[1],
    clippingRect: deserializedArray[2]
})

, which is valid and correct and nice with regard to your question.

Off course, there have to be suitable conditions for this - in Javascript this is much more viable than in, say, C. In javascript, this even gave birth to now widely used structural notation that grew popular as a lighter counterpart to XML. It's called JSON (you may have already heard about it).


答: The best "rule" I've heard is that name lengths should be proportional to the length of the scope of the variable. So an index i is fine if the body of the loop is a few lines long, but I like to use something a little more descriptive if it gets to be longer than 15ish lines.

Title: Are short identifiers bad?

Body:
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf


答:
Story points are a relative value.  How much work is this story, compared to another one?
Once you have reference, you should be able to estimate all stories regardless of the project they are for.  It might be that a similar task in one project is always more work than in the other - but you can still compare the amount of work to your reference point.

The speed in storypoints per sprint should then then depend on the team, not on the project they work for.

You can then make estimates: This work for project 1 will be done if project 1 gets full priority.
If we pull in these stories from project 2, then this much will get done.

Title: How to compute scrum burndown chart when projects overlap?

Body:
In my team we have a multiple projects, some short term and some long term. The team is required to deliver these projects on different dates and the effort to deliver these is run in parallel with the team working on stories for more than one project during each sprint.

When trying to compute our burndown we aren't sure what to do.

As the team is split between projects the velocity can change dramatically week-on-week as people shuffle to the tasks best suited for their specialty across the projects. This makes it difficult to create a reliable and meaningful burndown chart for each project.

However if we combine the stories into a single burndown chart how can we track against the release if the release dates are different and it isn't obvious which points remain for each project.

Is there a good method for dealing with this?


答:
When a SCRUM team works on stories from multiple projects, you should have several burn-down charts:

One chart indicating the progress on the stories within the current sprint. This chart is updated daily by the team to indicate how they are progressing to the sprint-goal of that sprint. Where the stories on the chart come from should not matter for the chart.

One chart per project to keep track of how the project is progressing towards its release date. This chart is mainly for the project manager(s) to keep track of the progress of their project(s) and should be updated only when a story for that project is delivered by the team.

The velocity measurement is SCRUM is meant to give the team a measure for how consistent they are estimating the amount of work/complexity that they can handle in a sprint.
This can only work if there is a single golden standard to use as a reference for a unit of work/complexity.

The golden standard can (and will) differ between teams, but it should be consistent within a team, even if that team works on stories from different projects.

The recommended way to establish such a golden standard is to pick a story of medium effort and give that 3 story points. Then you estimate all other stories relative to that golden standard.


答:
I will use an identifier that describes the variable, irrespective of length.

The cases of i,j and k are in themselves so ubiquitous they are self describing, you automatically know they are loop indices.  You could also say the same for  :

foreach loop (Strings s : myString)

However, IDE's now provide code completion tools so the only negative side effect of very long and descriptive identifiers has been removed afaik.

I will happily add and extra word to an identifier, if its required to explain the purpose of the variable.

Title: Are short identifiers bad?


答:
Each variable should have a meaning, and its name is a part of that meaning. And a very important part, since it helps the reader to understand what it is for without digging deeper into algorithm. i, j are obvious to be used as indices, they are short, but very informative. bnt is ugly, close or closeButton are meaningful. So being short or long is not the most important criterion for the variable name, it should be meaningful. The meaningfulness strongly depends on the context. For example, you can give a very short name like n to the local string variable which is used in a small block of the code say 10 lines and refers to the name of a property (v for value is another example).

So variable names should be informative and it doesn't matter they short or long.

Title: Are short identifiers bad?


答:
Indented code must have arrived prior to 1958, since it was present - but not ubiquitous - in LISP and ALGOL. The earliest I can locate is COMTRAN which was introduced in 1957, although I can only find the 1960 manual only (see page 90ish). This indentation differs from the modern conception since COMTRAN lacks the block structure of most languages since ALGOL but I think it should still count.

I suspect that this is not actually the first example but I cannot locate any earlier.

Updated

It has occurred to me that to a meaningful degree indentation probably predates programming. Indentation was likely used in instruction lists prior to anyone writing computer programs. Unfortunately I can't find any good examples of this.

Title: Origins of code indentation

Body:
I am interested in finding out who introduced code indentation, as well as when and where it was introduced.

It seems so critical to code comprehension, but it was not universal. Most Fortran and Basic code was (is?) unindented, and the same goes for Cobol.

I am pretty sure I have even seen old Lisp code written as continuous, line-wrapped text. You had to count brackets in your head just to parse it, never mind understanding it.

So where did such a huge improvement come from? I have never seen any mention of its origin.

Apart from original examples of its use, I am also looking for original discussions of indentation.


问:
How to handle passing multiple dependencies in a module hierarchy
So I have my application consisting of a number of modules in a module hierarchy. Furthermore let's also assume each module is a class and we have a tree of classes where the classes at the top are using the classes below, to make it more simple.

A class A1 at the very bottom may depend on some input parameters. class B1 is above class A1 and is creating and using instances of class A1. Therefore it has to pass the dependencies needed by the instances of class A1 into them. If it can't create these dependencies from some operations, class B1 now has it's on dependencies but additionally the dependencies of class A1.
The higher we go the more these dependencies will add up so that the toplevel class will need to know all the dependencies unless they can be created at a lower level.

This means if class A1 my program is dependent on the current temperature, I have to pass this to the toplevel class which then passes it to the next class and so on until it arrives at the very bottom in class A1. If I do that, I make the state explicit but it also means that I have methods or classes that take many parameters.

Variables

What if the temperature is may change while the application is running - is there a way to avoid passing it all the way down the class tree without giving away explicit state? How would you guys handle this?

Constants

What if the temperature is a constant that will never change while the program is running? Does this give us more options to avoid passing it always as an argument? I could see someone using a global configuration (singleton) but it will make it harder to test right?

I could also pass not the temperature itself but a configuration object. This would mean class B1 does not receive for example a temperature and a airpressure parameter but gets a configuration object passes it to class B1 and class B2 where class B1 only needs the airpressure and class B2 only needs the temperature. Is that a good approach? What are the pros/cons?

答:
This is exactly the reason why DI containers exist. I will give you an example for Castle Windsor, but it should apply to other containers, with some modifications.

Class definitions:

```<code>public class A1
{
    public A1(decimal temperature)
    {
        _temperature = temperature;
    }

    private readonly decimal _temperature;

    // what follows is specific to the possible methods that make use of temperature
}

public class B1
{
    public B1(A1 a1)
    {
        _a1 = a1;
    }

    private readonly A1 _a1;

    // possible methods that make use of a1
}
</code>```

Container configuration:

```<code>// this assumes a C# environment
var temperature = Convert.ToDecimal(ConfigurationManager.AppSettings["temperature"]);

IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<A1>().DependsOn(Property.ForKey<decimal>(temperature)));
container.Register(Component.For<B1>());
container.Register(Component.For<MainForm>());
</code>```

This is a very basic example of what you can do with a container. The types used by the application must be made known to the container. When asked to create an instance the container will search the constructor for dependencies and will create them from the types it knows about. This is called constructor injection because the constructor is used to specify the dependencies for a class.

Type resolving:

Dependency injection introduces a concept called composition root, which is the place where all the components of your application are put together (the configuration section above is placed in here). The container should (I'm using should because there are some exceptions to this rule) be used explicitly only in the composition root.

None of the classes of your application that are not related to infrastructure are allowed to have the container as a dependency. If you need to break this rule then it's a clear indication of a design flaw.

Let's assume that we have a desktop application, with a main form that uses our B1 class.

```<code>public class MainForm : Form
{
    public MainForm(B1 b1)
    {

    }

    ...

    // do something with b1
}
</code>```

The composition root for this application is the entry point (for .net windows applications the entry point is Program.cs). I have made MainForm known to the container in the configuration code above. All I have to do now is obtain an instance of MainForm and show it to the user.

```<code>public static class Program
{
    // container configuration goes here

    // type resolving follows
    var mainForm = container.Resolve<MainForm>();

    // show main form the the user

    ...
}
</code>```

At this point, the container searches its list of known types for MainForm, looks in the constructor for any dependencies and it tries to resolve them. It will move through the hierarchy down to the last type. By the time it finishes it will have created instances for all the types in the hierarchy (if the types are found in the container).

If the temperature is variable then I would use a class with a simple method called GetTemperature and inject that class wherever I need it. The method presumably performs some logic to retrieve the temperature. If the system must respond to temperature changes then the classes that depend on it can be observers of the class that emits these changes.

If a class depends on multiple configuration constants then it's perfectly fine to group them in a single class and pass that class as dependency where it's needed. Castle has an adapter that helps in this particular case.

I recommend reading Mark Seemann's book (Amazon link) on dependency injection, it is very well written and is, in my opinion, the best book on the subject.

Body:
This is exactly the reason why DI containers exist. I will give you an example for Castle Windsor, but it should apply to other containers, with some modifications.

Class definitions:

public class A1
{
    public A1(decimal temperature)
    {
        _temperature = temperature;
    }

    private readonly decimal _temperature;

    // what follows is specific to the possible methods that make use of temperature
}

public class B1
{
    public B1(A1 a1)
    {
        _a1 = a1;
    }

    private readonly A1 _a1;

    // possible methods that make use of a1
}

Container configuration:

// this assumes a C# environment
var temperature = Convert.ToDecimal(ConfigurationManager.AppSettings["temperature"]);

IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<A1>().DependsOn(Property.ForKey<decimal>(temperature)));
container.Register(Component.For<B1>());
container.Register(Component.For<MainForm>());

This is a very basic example of what you can do with a container. The types used by the application must be made known to the container. When asked to create an instance the container will search the constructor for dependencies and will create them from the types it knows about. This is called constructor injection because the constructor is used to specify the dependencies for a class.

Type resolving:

Dependency injection introduces a concept called composition root, which is the place where all the components of your application are put together (the configuration section above is placed in here). The container should (I'm using should because there are some exceptions to this rule) be used explicitly only in the composition root.

None of the classes of your application that are not related to infrastructure are allowed to have the container as a dependency. If you need to break this rule then it's a clear indication of a design flaw.

Let's assume that we have a desktop application, with a main form that uses our B1 class.

public class MainForm : Form
{
    public MainForm(B1 b1)
    {

    }

    ...

    // do something with b1
}

The composition root for this application is the entry point (for .net windows applications the entry point is Program.cs). I have made MainForm known to the container in the configuration code above. All I have to do now is obtain an instance of MainForm and show it to the user.

public static class Program
{
    // container configuration goes here

    // type resolving follows
    var mainForm = container.Resolve<MainForm>();

    // show main form the the user

    ...
}

At this point, the container searches its list of known types for MainForm, looks in the constructor for any dependencies and it tries to resolve them. It will move through the hierarchy down to the last type. By the time it finishes it will have created instances for all the types in the hierarchy (if the types are found in the container).

If the temperature is variable then I would use a class with a simple method called GetTemperature and inject that class wherever I need it. The method presumably performs some logic to retrieve the temperature. If the system must respond to temperature changes then the classes that depend on it can be observers of the class that emits these changes.

If a class depends on multiple configuration constants then it's perfectly fine to group them in a single class and pass that class as dependency where it's needed. Castle has an adapter that helps in this particular case.

I recommend reading Mark Seemann's book (Amazon link) on dependency injection, it is very well written and is, in my opinion, the best book on the subject.


问:
global try-catch in presentation layer
I have a 3-layered app structured as follows.

Presentation Layer (ASP.NET MVC project)

Business Logic Layer (Services for controllers in PL)

Data Access Layer (Repositories)

Each Controller in PL interacts with its service in BLL, which in turn has access to Repositories in DAL.

Is it a good practice to do a "global" try-catch in the PL? That way if exception is thrown in DAL, for example, I can display the error message to the user. Or is there a better way to do this?

答:
Your presentation layer should have a fault barrier. All decent frameworks will let you configure it once only, for unexpected exceptions. So try-catch does not pollute every controller method.

When you want to show the error message to the user, then catch the exception in the specific controller. However, this is only useful if the user can do something about it, so don't catch all exceptions in the controller catch block - let most of them fall through to the fault barrier.

See this article http://www.oracle.com/technetwork/articles/entarch/effective-exceptions2-097044.html. It's about Java, so the checked/unchecked distinction doesn't apply, but you should still follow the pattern of faults vs contingencies

Title: global try-catch in presentation layer


答: In ASP.Net, you can setup an Error page in your Web Config that can handle the display of any uncaught errors in the method of your choosing.  Setting up a global try/catch can cause issues in catching your errors.  Your error page should be setup to show your error message and, if you want the user to see the error, display any error you've received.</p>

Title: global try-catch in presentation layer

Body:
I have a 3-layered app structured as follows.

Presentation Layer (ASP.NET MVC project)

Business Logic Layer (Services for controllers in PL)

Data Access Layer (Repositories)

Each Controller in PL interacts with its service in BLL, which in turn has access to Repositories in DAL.

Is it a good practice to do a "global" try-catch in the PL? That way if exception is thrown in DAL, for example, I can display the error message to the user. Or is there a better way to do this?


问:
Conception and design before coding: how much is this true?
I learned at school as well as I read everywhere else that a good development methodology needs conception and design before coding properly.

That is not a new information even for a beginner programmer. However, I wonder if this a good advice because since I started developing in several programming languages I never succeeded to design and conceive everything since the start.

I mean, I always melted design, conception and programming. Am I the worst developer in the world, or is the idea we learn at school just an old meaningless religious dogma?

How can we even conceive and design something we  never experienced and programmed before? Is not that ridiculous? Does not programming lead the conception and design instead?

答:
It is absolutely true. The larger and more complex the requirement, the more true this is.

For a small console app to calculate the Fibonacci sequence, you may not need more than a few minutes of thinking about how to structure the algorithm and the UI (which, yes, could simply be stdin and stdout).

But how about a real-time trading platform expected to do millions of transactions a second, distributed globally and  that requires 99.9999 of uptime and 100% of correctness? Would you just jump into coding that?

There are lots of other options between these two extremes.

Take a look at project Euler. Solve some problems, in the presented sequence. You will find out that in order to solve some of the problems in reasonable time, you need to actually think before jumping into code.

If you do not need to take time to think and design your program before starting to code, you are either working on trivial things or missing something larger.

I never succeeded to design and conceive everything since the start

No one does for anything but the most trivial of problems. Again, the larger and more complex the project, the more true this is - designs will be have mistakes, things that are overlooked etc...

The art is in designing in high level first, seeing if the large pieces fit. Then get a list of priorities - starting to work on the most crucial / infrastructure first. Then we go and break down the larger pieces to smaller ones, making sure each larger piece is composed of pieces that make sense.

This takes time and effort - and may not be complete or fully correct at the beginning.

But this is why it is called soft-ware and not hard-ware. It is malleable and can be changed.


答:
I learnt at school as well as I read everywhere else that a good development methodology needs conception and design before coding properly.

This is true.

However, I wonder if this a good advice because since I started developing in several programming languages I never succeeded to design and conceive everything since the start.

And there's your problem.

For most non-trivial problems, you're going to need to do some thinking to figure out how things are going to work - how things are going to fit together. Paradoxically, for most non-trivial problems, there's no way you'll be able to plan everything out. There's just too much unknown for you to account for, too much change that will occur during development. Agile has gained the traction it has because it accepts this second half of the deal: people are not omniscient and change is constant.

So it's certainly true that you need to do design ahead of time, but it's also true that it's impossible to only design ahead of time.

Title: Conception and design before coding: how much is this true?

Body:
I learned at school as well as I read everywhere else that a good development methodology needs conception and design before coding properly.

That is not a new information even for a beginner programmer. However, I wonder if this a good advice because since I started developing in several programming languages I never succeeded to design and conceive everything since the start.

I mean, I always melted design, conception and programming. Am I the worst developer in the world, or is the idea we learn at school just an old meaningless religious dogma?

How can we even conceive and design something we  never experienced and programmed before? Is not that ridiculous? Does not programming lead the conception and design instead?


答:
conception is the key
design can always be changed
programming will have to meet the requirements of the fully conceived app.

1st whats the point, 2nd how does it need to be accessed, 3rd who the user is, 4th lay out a full SOW scope of the work define in specific terms all this application is to do. and how each function you add will work.

before any choices are made as to the architecture of you web app, plan and think it through completely.

then pick the best stack

I am a LAMP developer

so I tend to narrow the question to what php framework i will use. and the front end scripts i will need to make it do all the things i need it to do in a ideal way

to add this, learn to use MVC frameworks, ZEND and CAKEPHP are the best rapid development frameworks ( PHP)


答: I agree very much with the other answers here, but would like to point out one other factor that I think is often overlooked. A good name is often one that is idiomatic to the code. This can be on a language level, algorithm level or some internal idioms for the codebase at hand. The point is that while the name may mean nothing to someone that does not know the domain of the code, it may still be the best name in the given context.</p>

Title: Are short identifiers bad?


问:
Why XML is meant to be Software and Hardware independent?
While studying the features of XML, I got to know that XML is software and hardware independent. Can anyone explain me why it is meant like that?</p>

答: Hardware independent means it can be handled the same way even in different kinds of computer architectures. For example, XML isn't affected by endianness.</p>


问:
How do programming language translators work?
I'm a programmer and I'm looking to play around with translating one language to another. Say C# to Lua. I'm curious as to how translating languages like that works? I would think there is some kind of standard methodology that I could perhaps look into for this or is it pretty raw? </p>

答:
A parser can take source code from a language and turn it into a sort of tree. Since any language can be represented this way, translating is a matter of turning the source code from one language into a syntax tree and then reversing the process to turn that tree into the source code of the target language.

There are, of course, finer details - the languages must have corresponding features, so there may be programs in language A that can't be expressed directly in language B; you'd have to stick to the subset of features that's common to both. The same could be said of the standard libraries - you could translates a printf in C to a System.out.printf in Java but there are things that have no obvious translation.

Further reading: The nature of Lisp


问:
How to adhere to the open-closed principle in practice
I understand the intent of the open-closed principle. It's meant to reduce the risk of breaking something that already works while modifying it, by telling you to try to extend without modifying.

However, I had some trouble understanding how this principle is applied in practice. To my understanding, there are two ways to apply it. Beofore and after a possible change:

Before: program to abstractions and 'predict the future' as much as you can.
For example, a method drive(Car car) will have to change if
Motorcycles are added to the system in the future, so it probably
violates OCP. But the method drive(MotorVehicle vehicle) is less
likely to have to change in the future, so it adheres to OCP.

However, it's quite difficult to predict the future and know in
advance what changes are going to be made to the system.

After: when a change is needed, extend a class instead of modifying it's
current code.

Practice #1 isn't hard to understand. However it's practice #2 that I'm having trouble understanding how to apply.

For example (I took it from a video on YouTube): let's say we have a method in a class that accepts CreditCard objects: makePayment(CraditCard card). One day Vouchers are added to the system. This method doesn't support them so it has to be modified.

When implementing the method in the first place we failed to predict the future and program in more abstract terms (e.g. makePayment(Payment pay), so now we have to change the existing code.

Practice #2 says we should add the functionality by extending instead of modifying. What does that mean? Should I subclass the existing class instead of simply changing it's existing code? Should I make some kind of wrapper around it just to avoid rewriting code?

Or does the principle not even refer to 'how to correctly modify/add functionality', but rather refers to 'how to avoid having to make changes in the first place (i.e. program to abstractions)?

答:
I understand the intent of the open-closed principle. It's meant to reduce the risk of breaking something that already works while modifying it, by telling you to try to extend without modifying.

It is also about not breaking all the objects that rely on that method by not changing the behavior of already existing objects. Once an object has advertised  behavior changing it is risky as you are altering the known and expected behavior of the object without knowing exactly what other objects expect that behavior.

What does that mean? Should I subclass the existing class instead of simply changing it's existing code?

Yup.

"Only accepts credit cards" is defined as part of the behavior of that class, via its public interface. The programmer has declared to the world that this object's method only takes credit cards. She did it using a kinda not particularly clear method name, but its done. The rest of the system is relying on this.

That might have made sense at the time, but now if it needs to change now you should make a new class that accepts things other than credit cards.

New behavior = new class

As an aside - A good way of predicting the future is to think about the name you have given a method. Have you given a really general sounding method name like makePayment to a method with specific rules in the method as to exactly what payment it can make? That is a code smell. If you have specific rules these should be made clear from the method name - makePayment should be makeCreditCardPayment. Do this when you are writing the object the first time and other programmers will thank you for it.


问:
I need a true random number generator web service
Random.org provides 200k free random bits (only 6250 32-bit integers!) from the analog world (cf.) per IP per day.

Does anyone know of an alternative web service that provides more on-demand  random bits per day?

(paying is OK as long as the price is "within expectations" of 1000×1024bits per usd cent) (random.org's paid service charges 100× this price)

答:
here is another quantum based generator, with a rest api no less :

http://photonics.anu.edu.au/qoptics/Research/qrng.php

Researchers at the ANU are generating true random numbers from a
  physical quantum source. We do this by splitting a beam of light into
  two beams and then measuring the power in each beam.  Because light is
  quantised, the light intensity in each beam fluctuates about the mean.
  Those fluctuations, due ultimately to the quantum vacuum, can be
  converted into a source of random numbers.


问:
How do I get into R&D?
I'm beginning to think that I might be best suited for a job in R&D.  The reason being that I like jobs that allow me to be creative and I generally am more interested in solving puzzles than building things.  I really dislike jobs that just boil down to translating requirements into code.

Here's the kicker though:  I don't have a bachelor's much less a masters or phd.  Is it possible for me to land a job like this?

答: Get a PhD. Then, either apply for grants or apply for jobs in the private sector.</p>

Title: How do I get into R&D?


问:
Type systems: nominal vs. structural, explicit vs. implicit
I'm a bit confused about the difference between nominal and structural type systems. Can someone please explain how they differ?

From what I understand:

Nominal: Type compatibility is based on type name.

Structural: Type compatibility is based on the type structure, e.g. in C if 2 variables are struct types with different names but the same structure, then their types are compatible.

Now about explicit and implicit: why is it different from static and dynamic typing? In static typing, types will be explicit while in dynamic typing, types are implicit. Am I right?

答:
The best explanation I've seen of the distinction between (actually subsumption of) dynamic and static type systems is in this blog post by Bob Harper:

Dynamic languages are static languages

Its main point could be summarized as:

dynamic languages are those static languages with only one type


答:
I always allot time as follows:

1/3 Design

1/3 Development

1/3 Testing

Design: Not only visual, but also conceptual. Divide it into parts, both visually and by logic. Look for commonalities which are re-use and are a design pattern in themselves.

Development: Once you know your parts, code them. Then you integrate them.

Testing: Not just testing that the code was integrated and written properly, invariably there will be insights spotted and lessons learned and it'll create new ways to interact, new capabilities will be conceived and desired. Beware of scope creep.

In addition to these aspects, be aware that a project also has 3 phases on top of these phases.

The under-engineered first attempt

The over-engineered second attempt, from lessons learned from the 1st attempt.

The properly engineered 3rd attempt.

I have found that the better you do the design phase, that it minimizes the additional attempts. Instead of re-doing the whole thing, you might have just a sub-system that gets reworked.

I am a software developer, and software development manager for in-house, outsourced and off-shore development projects.