问:
How do you track what you and your team are working on day-to-day?
I'm struggling with how to keep track of what myself and people on my team actually do each day. I get a good broad picture by going over completed cards each week and stand-ups help a bit, but I feel like I don't have a good handle on the day-to-day workings of my team. Cards will stay in progress for days on end without an update at the daily stand-up, and some engineers are my team aren't the most communicative.

I've thought about implementing some sort of daily record that everyone fills out (via a mailing list or a shared google doc) but this seems fairly cumbersome and manual.

Monitoring GitHub activity does an ok job but can be a little bit overwhelming with how many emails it sends out everyday. I've thought about trying to build a digest system for it, but don't have the time to spare.

What strategies have you implemented to stay on top of what your team is doing everyday so that you can measure work on "in progress" tasks?

答:
I'm surprised that no one here has yet mentioned "followed" or "starred" repository messaging built into systems like GitHub or BitBucket.

Our technical stakeholders (project leads, development and support managers) all follow our issue and commit update histories on their relevant projects.  We have a small team (15 FTE + contractors), but this seems to work for us to

No one is measured on any of these things, but in addition to weekly status reports from the PM's, this gives a daily view into the project to at least keep everyone aware of what areas are being worked on so no one goes without visibility.

It's also helped to increase transparency across developers and contractors and our business liaisons which helps everyone be accountable to their deliverables schedules.

When combined with RSS feeds associated with specific repositories or across our entire organization, we've been able to limit emails (where wanted) and offer a similar set of data in real-time and in summary via RSS readers.  For some users this is Outlook so it's basically email for them, though slightly different, but for other users they use a full-fledged RSS client with all the extra filtering they need to customize it to their exact needs.

We ran into similar concerns about email volume at first, but our end-users came up with the RSS system without the Engineering Org having to do much besides suggest clients for those not using Outlook.  Worked for us, again around 20-30 FTE + Contractors throughout the year across multiple offices and time zones. YMMV, obviously.


问:
Understanding C# Delegates Structure
I've been trying to understand C# delegates using Pro C# 5.

In short, the author describes the motivation for delegates as a structured way of dealing with function pointers and callbacks or two-way communication between objects.

The part I find confusing is the syntax/implementation for this:

On the one hand, an object of delegate type is seen as the handler
or the one responsible for invoking some method or list of methods. To this end, it has
methods such as Invoke() etc.

On the other hand, the delegate type is used as a 'wrapper' with
which to pass around methods.

For example, it seems strange to me that a call to a delegate's GetInvocationList() returns an array of delegates. Shouldn't there be something else with which to wrap methods?

I expected there would be some other construct/type, say, MethodContainer which wraps methods. Then the syntax for adding methods to a delegate would be

```<code>class MyClass{ void Method(string s){} }

MyClass c = new MyClass();
MethodContainer container = new MethodContainer(c.Method);

delegate void MyDelegate(string s);
MyDelegate d = new MyDelegate();

d.Add(container);

d.GetInvocationList(); // returns array of MethodContainer
</code>```

答:
There actually is this sort of distinction made under the covers. Delegate is the single function wrapper, and MulticastDelegate is the type that is the composite form of Delegate. The confusing part is that Delegate isn't really exposed from the innards of the runtime. All delegates created by C# are multicast delegates, even if they only contain a single item.

This is because historically, delegates were largely there to make windows events work nicely, which often would have multiple listeners. Now that delegates are used more for functional programming approaches, it's a little more awkward in theory. In practice, very few people use the multicast functionality outside of events given its downsides (exceptions at any point of the chain will break it, and the caller won't know where, hard to debug) and because it's not exactly common knowledge.

ContentLicense: CC BY-SA 3.0

Title: Understanding C# Delegates Structure


答:
An alternative to some of the other answers (communication focused) is that perhaps the tasks on your note cards can be broken up into smaller pieces which you would then be able to get feedback on sooner.

With smaller pieces the team feels like they are accomplishing something every day which should reflect in the stand-up.

The drawback is these separate cards will likely rely a lot on each other. A team which is able to communicate very easily with each other is beneficial here, or pieces may not combine as well as they should. You may also need to hold some of the cards back if you need certain things done first.

That being said, people will still get stuck or find out a task is much more challenging than they, or you, anticipated from time to time. This is why it is still helpful to discuss issues openly in the stand-up where others can offer advice without judging the person having troubles.

To answer the issue of micro-management as some of the other answers have brought up: even though people will accomplish small tasks each day it will take a broader view of their accomplished work to get a sense how much each person is actually getting done, rather than judging them by their daily accomplishments.

I suggest this because I work on a team of 8, where communication is very easy and people are very approachable. We are given tasks that are never expected to take longer than two days worth of work. Sometimes these tasks are closely related and we need to keep each other updated on how we each go about our own piece. We are each responsible for reporting what we've accomplished every two weeks to our manager.

After reading the question again, I realize you may be asking this as a team member, not as a leader, and so you may not have control over your tasks.

You could suggest to your leader to break up the tasks more

If your work is getting blocked or depends on work by another team member, feel free to check with them on it and take a different task if you need to.

Title: How do you track what you and your team are working on day-to-day?

Body:
I'm struggling with how to keep track of what myself and people on my team actually do each day. I get a good broad picture by going over completed cards each week and stand-ups help a bit, but I feel like I don't have a good handle on the day-to-day workings of my team. Cards will stay in progress for days on end without an update at the daily stand-up, and some engineers are my team aren't the most communicative.

I've thought about implementing some sort of daily record that everyone fills out (via a mailing list or a shared google doc) but this seems fairly cumbersome and manual.

Monitoring GitHub activity does an ok job but can be a little bit overwhelming with how many emails it sends out everyday. I've thought about trying to build a digest system for it, but don't have the time to spare.

What strategies have you implemented to stay on top of what your team is doing everyday so that you can measure work on "in progress" tasks?


问:
What should I expect from a developers guide?
I'm willing, with some friends, to make a developers guide for an open source point of sale written in Java.

The thing is I have never written anyone and so I don't know exactly what to put in there to meet standards. I'm thinking about putting UML, and using Java doc but still I don't know what are the expectations of developers towards a developers guide.

How can we say a developer's guide is truly worth?

答:
Some of things I would look for in a library or program:

What it does, and what is it's intended purpose.  You said it's a point of sale system, but that still doesn't really tell me what all features the product has.

A setup guide so that I can get the system up and running.  Bonus points if you give me an automated process that will do this for me so I don't have spend a lot of time in configuration.

Any domain concepts I might need to understand the system.  A glossary of terms can be helpful.

A specification would also be good.  Knowing that a system does Foo because it's supposed to and not as a happy accident is helpful.

Code examples of its usage or ways to extend it.  If it's extensible or able to be integrated, then an example extension\integration is very instructive on how I might utilize the system.

Finally, architecture diagrams, and an overview of the codebase(s).


答:
This is a very marginal addition (and it isn't programmer specific), but I've had good success with Asana in recent projects.

For integration with existing online collaboration tools, look no further than Slack. It's built around a chatroom, but it serves as a fairly minimalist hub for other tools including Asana, GitHub, and Bitbucket. It has a decent collection of these "integrations," both pre-made and community-made, using the API that of course allows you to build your own.


问:
What is meant by "code rot"?
Please say that 'code rots' if you don't clean it. What does that mean?

Obviously code is text, not an organism that can change itself. So why does code 'rot' if you don't touch it? What makes it 'rot' and what does it actually mean?

Please explain, examples would be welcome.

答:
The general idea itself is simple - code that has remained untouched for an extended period of time and now does not compile/run without some effort. The question of "how" is a little more complicated.

Given a piece of code and a fixed environment, the system's behavior will not change. This determinism appeals to our general sense of logic.

The issue is that our environments are never static. We are running newer compilers, different IDEs, servers have been upgraded and OS patches have been issued. Generally speaking, even the hardware has changed. Seldom do these differences seem big. We accumulate them, one by one and then realize that the new environment does not still work with the old code.

The crux of the matter is, of course, that this is a gradual process that we do not really take note of while the code was, in some sense, out of sight. This is what leads to the feeling that the code rotted. Like some leftovers, we left it unattended in the refrigerator and now the whole container is spoiled.

It may be fair to say "environment drift" is a more precise term for what happened in this situation than "code rot", but the latter more specifically captures how it feels to the system maintainers. Hence the popularity of the term.

Title: What is meant by "code rot"?


问:
When should you call yourself a senior developer?

Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?

答: When you look back at your previous work and realize what crap it was. And you understand that you've gotten better but there are miles to go, and that learning is forever. </p>

ContentLicense: CC BY-SA 2.5


答:
In addition to Michael's answer which, while correct, is only part of the equation.

The other more common part is code that is continually updated, extended and modified. Since those processes are not 100% reliably perfect, code gets more and more bugs introduced to it over time. Worse, it tends to get more and more "correct but ugly/hacky" code. This reduces the integrity of the code, "rotting" it until it eventually falls apart.

Title: What is meant by "code rot"?

Body:
Please say that 'code rots' if you don't clean it. What does that mean?

Obviously code is text, not an organism that can change itself. So why does code 'rot' if you don't touch it? What makes it 'rot' and what does it actually mean?

Please explain, examples would be welcome.


问:
Simple unicode application?
I want to create simple language learning applications to help friends in learning languages. A simple Java console application would do the trick, but the Windows console does not seem to handle Unicode (and I need my software to work with all kinds of special letters at once).

Googling it, I get the idea there might be ways to actually make Unicode work in the Windows console, but it seems a bit overly complex, plus that it requires some effort from anyone running the program. I want to write programs that anyone without computer experience can run easily.

I wanted to try doing this in Python instead, as the IDLE console at least seemed to work with Unicode. But it has its own set of problems (I can't enter certain letters, like the é, without writing it elsewhere and pasting it in)

Now I'm considering building this as a web application or Swing application, to actually be able to make my program work with Unicode. But I feel I'm maybe overlooking something. Is there no easy way to make a Unicode console application that'd work on Windows?

答:
Dynamic Language Python is probably a better choice than Java for such an application, given its relative simplicity and less need for boilerplate code and operational middleware. I don't know about the IDLE console for Python 2, but IDLE for Python 3.4 handles Unicode characters well (I just tested it), as does Python 3 overall. Nicer IDEs such as Komodo and PyCharm (both of which have free versions) are great with Unicode characters. There are tutorials and explanations online (e.g. this one from Wikipedia) for various systems how to enter Unicode characters without copy-and-paste.

Web Application Console apps are simple, but not particularly attractive by modern standards. Much of the world has also moved beyond desktop GUI applications, embracing Web apps. Web apps offer you easier distribution to a wider audience and easier construction for high-polish looks. You will end up needing HTML, CSS, and some JavaScript skills in building the front end to a Webapp, in addition to whatever your app backend is. I recommend that you look into jQuery and its user-interface extensions. It's not the only JavaScript approach to building UIs, but it's very common and widely supported.  While this is more up-front investment, you will end up with a more valuable and forward-looking set of skills for yourself. If you decide on Python and a Webapp, I suggest you look into the Flask Web app framework.

Dynamic Language, Part 2 Python isn't unique in its ability to build nice Webapps. PHP, Ruby, and JavaScript are other popular options. They all can handle Unicode well. If you decide to try building your entire app in JavaScript, I recommend you look at Meteor.

Title: Simple unicode application?


问:
One boilerplate class or many similar classes?
Lets say I'm trying to model a variety of objects that are virtually identical, the only difference being their class variables.  Am I better off creating one boilerplate class and just calling the constructor with the specific variables, or creating a lot (in this case 100+) of essentially identical classes and hard coding their class variables (which will never change)?

To be clear:

Identical methods

Identical class variable names but different values

Identical intended functionality

To be clear, my language (Python) doesn't support interfaces that I'm aware of - some of the other similar questions seemed to get answers recommending that.  The other option that seems to make sense to me would be to create a base class with each field and method and then create a bunch of unique child classes that contain their unique values.

The amount of work to create all the child classes isn't significant to me - I've written a program that quickly parses a text file (that has all the unique values) and can write all the classes to a .py file quickly and easily.  Making changes down the road is rather easy for the same reason.

(somewhat) Related questions

Create many similar classes, or just one

Good Programming Practice for similar child classes

答:
100+ almost identical classes is crazy. Classes are organizational structures. Having dozens of them with almost no variation does't seem useful. It's over-specialization.

It sounds very much like you need a single class with a shared lookup-table that defines the shared info. Something like:

```<code>from collections import namedtuple

Lang = namedtuple('Lang', 'style points creator')

LANG_FORM = {
    'Python': Lang('dynamic', 84, 'Guido van Rossum'),
    'Java':   Lang('static', 65, 'James Gosling'),
    # ...
    'Pascal': Lang('static', 33, 'Niklaus Wirth')
}

class Protean(object):

    def __init__(self, name, form):
        self.name = name
        self.form = form
        self.lang = LANG_FORM[form] # optional

    # methods here
</code>```

Here LANG_FORM can be a global variable (quasi-constant), or it could be a class variable. Either way, each instance gets basically just a pointer back to its shared info (what you refer to as class variables). It doesn't even strictly need that, if you're willing to index LANG_FORM whenever you need it, rather than memorizing it in each instance.

If you want to have each of the instances depict itself based on its form/kind/quasi-class, add a __repr__ method:

```<code>def __repr__(self):
    classname = self.__class__.__name__
    return "{0}-{1}({2!r}, {3})".format(classname, self.form, self.name, self.lang.points)
</code>```

Then:

```<code>p = Protean('CPython', 'Python')

print p
</code>```

Yields:

```<code>Protean-Python('CPython', 84)
</code>```

Body:
100+ almost identical classes is crazy. Classes are organizational structures. Having dozens of them with almost no variation does't seem useful. It's over-specialization.

It sounds very much like you need a single class with a shared lookup-table that defines the shared info. Something like:

from collections import namedtuple

Lang = namedtuple('Lang', 'style points creator')

LANG_FORM = {
    'Python': Lang('dynamic', 84, 'Guido van Rossum'),
    'Java':   Lang('static', 65, 'James Gosling'),
    # ...
    'Pascal': Lang('static', 33, 'Niklaus Wirth')
}

class Protean(object):

    def __init__(self, name, form):
        self.name = name
        self.form = form
        self.lang = LANG_FORM[form] # optional

    # methods here

Here LANG_FORM can be a global variable (quasi-constant), or it could be a class variable. Either way, each instance gets basically just a pointer back to its shared info (what you refer to as class variables). It doesn't even strictly need that, if you're willing to index LANG_FORM whenever you need it, rather than memorizing it in each instance.

If you want to have each of the instances depict itself based on its form/kind/quasi-class, add a __repr__ method:

def __repr__(self):
    classname = self.__class__.__name__
    return "{0}-{1}({2!r}, {3})".format(classname, self.form, self.name, self.lang.points)

Then:

p = Protean('CPython', 'Python')

print p

Yields:

Protean-Python('CPython', 84)


问:
Is it ever OK for a conditional to have side effects?
I'm taking intermediate data structures course as a prereq for entry into the CS MS program at a University everyone in America has heard of. One line of code that was written in class caught my eye:

if (a > 33 | b++ < 54) {...}

This would not pass a code review at my workplace. If you wrote code like this in an interview, this would be a significant strike against you. (In addition to being a conditional with side effects, it's being clever at the expense of clarity.)

In fact, I've never seen a conditional with side effects, and Googling doesn't turn up much, either. Another student stayed behind after class to ask about it, too, so I'm not the only one who thought this was weird. But the professor was pretty adamant that this was acceptable code, and that he would write something like that at work. (His FT job is as a Principal SWE at a company you've all heard of.)

I cannot imagine a world in which this line of code would ever be acceptable, let alone desirable. Am I wrong? Is this OK? What about the more general case: conditionals with side effects? Are those ever OK?

答:
There is one semi-conditional side effect I can think of that is okay: while(iter.MoveNext())

That said, I think this falls mostly into the "never is a really big qualifier" category. I can think of a few rare cases where I've seen it be acceptable, but in general this is vile and to be avoided.

I also cannot think of a scenario where that particular line would be acceptable, but I also cannot think of a scenario where that particular line would be useful, so it is hard to imagine the context it is in.


问:
Is there any logical reason to auto-generate code documentation?
Automatic documentation generation can be done with a variety of tools, GhostDoc being one of the more prominent.  However, by definition, everything it generates is redundant.  It takes a look at names of methods, classes, etc. and outputs English that might explain them more verbosely.  In the best case, it does what the reader could already do in their head (examples taken from here):

```<code>/// <summary>
/// Initializes a new instance of the <see cref="Person"/> class.
/// </summary>
public Person() ...
</code>```

In the worst, it can actually end up generating bizarre documentation that is actually misleading in its attempt to heuristically figure out the meaning of names:

```<code>/// <summary>
/// Riches the text selection changed.
/// </summary>
/// <param name="richTextBox">The rich text box.</param>
private void RichTextSelection_Changed(System.Windows.Controls.RichTextBox richTextBox) ...
</code>```

It seems that the attitude with GhostDoc is, "it's intrinsically better to have some kind of formal XML documentation", but when that documentation is 100% redundant, why?  Isn't it just wasting a ton of space at best?

At my workplace, we have to document everything, and almost always with GhostDoc's auto-generated docs.  Do you do this, and are there any rational reasons not to simply leave code undocumented if you aren't going to actually write the documentation yourself?

答:
Avoid Tautology

The only time you should need any kind of documentation for code is to explain why a method/function is doing something, the name should suffice for what it is doing.

If you are doing something that isn't idiomatic, or violates the principle of least astonishment then documentation is required.

Auto generated documentation that is just a formatter for output of information is almost demanded by consumers of your code. Javadoc does this extremely well.

Not every thing should be documented manually

Things like getXXX/setXXX methods should be self explanatory, so auto-generating documentation that just lets you know they exists will be well received.


答:
As always with such questions, this is a matter of degree. If there were unequivocal proof that any side effect within an if expression always led to worse code, then it wouldn't be legal to create those expressions. Language designers may be ideosyncratic, fallible humans, but they're not that stupid.

That said, what are examples of justified side effects within an if? For instance, assume you're legally required to record all and any access to the property P of an entity E for audit purposes. (Imagine you're working in an uranium-enrichment plant, and there are very strict legal controls on what your code is allowed to do and how it's supposed to do it.) Then any if that checks that property will cause the side effect of the audit log being extended.

That's a pretty clear-cut cross-cutting concern, it doesn't affect your reasoning about the program state (very much), and you can implement it so that it's completely invisible and non-distracting when you review the line with the if (hidden away in the accessor, or even better via AOP). I'd say that's a pretty clear case of a side effect that's not a concern. Similar situations might be imagined when you just want to count branch executions for profiling purposes, etc.

The more these mitigating circumstances disappear, the stranger the construct will become. If a particular loop type (e.g. if((c = getc()) == 'x') { quit(); } is well-known and accepted by the language community, then it's much less of a problem than when you invent it spontaneously, etc. Your example line falls short of that standard, but I could imagine much, much more horrible ones that I won't even type, they're so horrible.

Title: Is it ever OK for a conditional to have side effects?

Body:
I'm taking intermediate data structures course as a prereq for entry into the CS MS program at a University everyone in America has heard of. One line of code that was written in class caught my eye:

if (a > 33 | b++ < 54) {...}

This would not pass a code review at my workplace. If you wrote code like this in an interview, this would be a significant strike against you. (In addition to being a conditional with side effects, it's being clever at the expense of clarity.)

In fact, I've never seen a conditional with side effects, and Googling doesn't turn up much, either. Another student stayed behind after class to ask about it, too, so I'm not the only one who thought this was weird. But the professor was pretty adamant that this was acceptable code, and that he would write something like that at work. (His FT job is as a Principal SWE at a company you've all heard of.)

I cannot imagine a world in which this line of code would ever be acceptable, let alone desirable. Am I wrong? Is this OK? What about the more general case: conditionals with side effects? Are those ever OK?


问:
How to avoid redundant code in designing inheritance in C++
Say I have a Base class called Car and it has 3 derived  classes say Ford, Honda and  Audi.

The issue is, all three derived classes have exactly same code but minor difference in calling member functions of  their respective engines (these engines have separate class).

For example, Ford class calls code which is exactly same as other two  classes  but do call something like ford_engine-> start(),  ford_engine->clean() etc.

```<code>//ly  honda  calls   honda_engine->start()   honda_engine->clean();

//ly  Audi calls audi_engine->start()  audi->clean();
</code>```

Now here the issue is, it has redundant code in all three places with minute difference. How can I have code at one place, most  probably in base class and all derived classes use same code?

答:
First of all, Ford, Honda and Audi probably should not be classes derived from Car. Derivation should reflect differences in behavior on an abstract level.

In this case, it probably makes more sense to simply have a Car object with a field identifying the manufacturer. The Car owns an engine--but in a typical case, you don't need a different class for each brand of engine either; at an abstract level, the brand is generally irrelevant.

As such, you can have something like:

```<code>class Car {
    class Engine {
        enum { diesel, piston, rotor, electric, hybrid } type;

        int HP;
        int torque;
        int max_rpm;

        bool running;

        void start() { running = true; }
        void stop() { running = false; }
        // ...
    } engine;

    std::string brand;
    std::string model;
};
</code>```

In a few cases you honestly need to model an engine at a level of detail where things like firing order really matter, and you'll need much more detail than this. It should still be at a behavioral level though. If you had a Ford_motor vs. Honda_motor the brand should still really be a short-hand for behavioral differences. You really want to maintain the most abstract view you can though, so you usually want to model an engine (car, etc.) in terms of behavior. The difference between a Ford and a Honda motor should be things like one has higher torque and the other higher red-line than the other; these differences can be modeled quite easily by supplying suitable parameters when instantiating the object. If Ford and Honda were to produce engines with identical characteristics (not just power, but power curves, etc.) then the difference in brand is irrelevant to your modeling.

Oh, and no you should not have a getEngine as a member of a Car. A car is a car. It has an engine. If you provide a getEngine at all, it should be a member of AutoPartsStore or something on that order (but unless you're dealing with buying and selling engines, you probably shouldn't have such a thing at all).

When a person starts their car, the don't get the engine and start the engine. They start the car and after they do so (successfully), the car is running. Forcing a client to use a getEngine and start the engine is both crappy from a coding viewpoint and from a modeling viewpoint--starting my car does more than just start the engine. It also controls things like some of the lights, the radio, heating/air conditioning, and so on. One of the basic points of object-oriented programming is to protect client code from dealing with all these internal details, not to force them to deal with the details and use crappy getXxx() syntax to do it!

Body:
First of all, Ford, Honda and Audi probably should not be classes derived from Car. Derivation should reflect differences in behavior on an abstract level.

In this case, it probably makes more sense to simply have a Car object with a field identifying the manufacturer. The Car owns an engine--but in a typical case, you don't need a different class for each brand of engine either; at an abstract level, the brand is generally irrelevant.

As such, you can have something like:

class Car {
    class Engine {
        enum { diesel, piston, rotor, electric, hybrid } type;

        int HP;
        int torque;
        int max_rpm;

        bool running;

        void start() { running = true; }
        void stop() { running = false; }
        // ...
    } engine;

    std::string brand;
    std::string model;
};

In a few cases you honestly need to model an engine at a level of detail where things like firing order really matter, and you'll need much more detail than this. It should still be at a behavioral level though. If you had a Ford_motor vs. Honda_motor the brand should still really be a short-hand for behavioral differences. You really want to maintain the most abstract view you can though, so you usually want to model an engine (car, etc.) in terms of behavior. The difference between a Ford and a Honda motor should be things like one has higher torque and the other higher red-line than the other; these differences can be modeled quite easily by supplying suitable parameters when instantiating the object. If Ford and Honda were to produce engines with identical characteristics (not just power, but power curves, etc.) then the difference in brand is irrelevant to your modeling.

Oh, and no you should not have a getEngine as a member of a Car. A car is a car. It has an engine. If you provide a getEngine at all, it should be a member of AutoPartsStore or something on that order (but unless you're dealing with buying and selling engines, you probably shouldn't have such a thing at all).

When a person starts their car, the don't get the engine and start the engine. They start the car and after they do so (successfully), the car is running. Forcing a client to use a getEngine and start the engine is both crappy from a coding viewpoint and from a modeling viewpoint--starting my car does more than just start the engine. It also controls things like some of the lights, the radio, heating/air conditioning, and so on. One of the basic points of object-oriented programming is to protect client code from dealing with all these internal details, not to force them to deal with the details and use crappy getXxx() syntax to do it!


问:
How to abide the "allocate in caller" rule when the size is computed in the callee?
Let's say we have an opaque type handle_t that is managed through a simple interface with functions such as:

```<code>handle_t *handle_init(void);
int handle_do(handle_t *);
void handle_free(handle_t *);
</code>```

The problem is that the size cannot be always determined in the initialization step and it has to be calculated in handle_do. One solution I have seen is calling handle_do two times, the first of which returns the size needed to allocate, but doesn't that affect the performance?

Is it a bad practice to allocate or reallocate memory in handle_do? Does it even matter when using handle types (since the init/free routines are made clear)?

答:
Your question is a little bit unclear. There is no "size" in your code example, I guess you are talking about the size of some internal array of the type "handle_t". I further assume at the time when handle_init is called, it is not clear how often handle_do will be called, or which additional parameters to handle_do will be passed, with different impact on the needed memory.

Actually, from a viewpoint of the user of your API, it should not matter how and where the allocation is done. If "handle_t" is an opaque type, your module should abstract away the internal memory allocation strategy from the user of your module. If and where you alloc, realloc and free any internal data structures should be kept hidden from outside. Under no circumstances the user of the module should have to call handle_do twice by himself (in an "calculate mode" and an "allocate mode") if the only reason for the double call is the memory calculation. That would unintuive and thus error prone.

So what to do internally, inside of your module? This depends. If I got you right, you are thinking about either doing some realloc in handle_do, or alternatively doing some of the memory size calculation steps twice, once just for finding out how much memory you are going to allocate, and once for the actual allocation. Both can be viable strategies, and both have some drawbacks. Lots of reallocations can have a negative impact on performance, but doing some time-intensive calculations twice, too, and the latter can make your code more complicated, so there is always a trade-off.

As a compromise, I suggest you check if you can implement your type along the lines of the following example: the std::vector implementation in C++.

A std::vector has a size and a capacity, where the size is always less or equal the capacity. When a vector operation increases the size beyond the capacity, the capacity is automatically increased (by a multiplicative factor, not just by 1!). This will lead to some internal reallocation, but for most real-world cases not too many reallocations. The user of a vector can also ask for more capacity at the "initializiation", so this can reduce the number of necessary reallocations at later point in time.

So in your case: check if handle_init can do some small allocation beforehand, and if handle_do notices that the preallocated memory is too small, it will automatically reallocate (with some extra margin if you expect further operations which might need even more internal memory).


问:
How to format Android view IDs
I struggle with this every time I work on a project. I am not entirely sure what the standard conventions are for creating view ids. I usually use something like

```<code>view_more_button
</code>```

but then if we have, let's say, multiple dialogs with a view more button then I'll start doing

```<code>view_more_button_dialog1
</code>```

and from there it just spirals downward.
Any suggestions?

答:
I usually prefix resource IDs with the "component" they belong to. Note that I say resource IDs and not View IDs because this applies to other resources too (String for example).

Specifically for views, I further add the view type after the component prefix.

Here's a concrete example:

```<code>login_button_done (View ID)
login_ok (String resource)
login_forgot_password (String resource)
dialog_button_view_more (View ID)
dialog_label_warning (View ID)
</code>```

One advantage of this approach is it makes it easier for IDE auto-complete. The downside is more keystrokes at the time of creating the views/String resources.

I have seen developers use a convention that puts the prefixes in the other order (i.e., viewtype_component_id). You should pick whatever suits your needs the best and just remember to stick to it throughout.

Not directly related to the question - but for some of my larger applications where the number of resources (especially strings) is very large, I also prefer to split up the strings into multiple files by component. For example, I'd have strings_login.xml, strings_settings.xml etc.

Specifically for dialogs, your view hierarchy would rarely (never ??) contain two dialogs simultaneously, so it is okay to re-use view IDs. In fact, I do sometimes create a few generic View IDs for this purpose.

Title: How to format Android view IDs

Body:
I usually prefix resource IDs with the "component" they belong to. Note that I say resource IDs and not View IDs because this applies to other resources too (String for example).

Specifically for views, I further add the view type after the component prefix.

Here's a concrete example:

login_button_done (View ID)
login_ok (String resource)
login_forgot_password (String resource)
dialog_button_view_more (View ID)
dialog_label_warning (View ID)

One advantage of this approach is it makes it easier for IDE auto-complete. The downside is more keystrokes at the time of creating the views/String resources.

I have seen developers use a convention that puts the prefixes in the other order (i.e., viewtype_component_id). You should pick whatever suits your needs the best and just remember to stick to it throughout.

Not directly related to the question - but for some of my larger applications where the number of resources (especially strings) is very large, I also prefer to split up the strings into multiple files by component. For example, I'd have strings_login.xml, strings_settings.xml etc.

Specifically for dialogs, your view hierarchy would rarely (never ??) contain two dialogs simultaneously, so it is okay to re-use view IDs. In fact, I do sometimes create a few generic View IDs for this purpose.


问:
Could the creation of many methods in Java affect performance?
I was told by a colleague that in Java, the performance may be worse if we create more methods, stacking many methods calling over them in JVM, specially in a Java EE environment.

This seems to somewhat defeat the concept of object oriented programming. Like if we write long methods - what isn't good for code readability - we can achieve more performance due to less methods in JVM stack.

So, write many methods who call and interact with each other is worse to performance than write a few long methods to use less stacks in JVM? Is this is a correct affirmation?

答:
As others said, in Java its generally better to use lot of short methods, because they are JITed and inlined better.

But it's plausible that in EE enviroment situation can be different. At least for method that are not simply called, but there is aditional overhead because of 1) Transaction handling, 2) Interceptors 3) EJB remote calls (stay away from highly granual remote calls)

But if you split large method into multiple private methods, these overheads should not happen.

tl,dr:
Method call itself is not problem, additional overhead is (and you have controll over it)

PS: I would not even consider NOT splitting methods for performance reasons untill proven there actually is some performance problem. With clearer code you usually achieve better performance, because you much easier identify parts that are 1) not actually needed 2) are called multiple times with same result


问:
Unevenly distributed random number generation
Let's say I have to generate random number from 1 to 100, however, the probability of each number is not 1/100, but a predefined probability.

How to generate that number? I use Ruby/Python.

答: the algorithm itself is easy: create an array with all the weights' cumulative sum. After that you generate a [0-1) uniform random number and just binary search that number multiplied with the sum of the weights and the index will be the number you will need to generate.


问:
How does the Common Language Runtime improve performance?
I read on the wikipedia article for Common Language Runtime that one of the benefits that the runtime provides is "Performance improvements".

Executing managed code (Or bytecode) must surely always be slower due to additional overhead for JIT compilation than executing native code. How then is it possible that the CLR causes "Performance improvements"?

Update:

I have looked at the question and answers to What backs up the claim that C++ can be faster than a JVM or CLR with JIT?, but it has not been helful as that question is actually asking why C++ would be faster rather than slower. What I am interested in is how it is possible, from an architectural point of view, that managed code could lead to performance improvements

答:
A CLR implementation does not necessarily interpret anything. In fact, the desktop CLR by Microsoft doesn't even have an interpreter, it always JIT compiles everything. So while CIL bytecode is read from disk and kept in memory, it is compiled to proper, fully fledged machine code which is then executed.
Thus only slowdowns that can be attributed to the execution model (as opposed to object model, memory management, CLR services, libraries, etc.) are:

Higher launch latency, i.e. the period between starting an application and its functionality being all there. This step can even be skipped via NGen.

Missed compiler optimizations caused by the desire to keep the aforementioned latency reasonable,


答:
In my world, a read from memory may be considered a side effect (e.g. memory mapped IO).

Now, consider the following:

```<code>    while( ( *memory_mapped_device_status_register & READY_FLAG) == 0) {
       // Wait
    }
</code>```

And compare to:

```<code>    status = *memory_mapped_device_status_register;
    while( ( status & READY_FLAG) == 0) {
        // Wait
        status = *memory_mapped_device_status_register;
    }
</code>```

Did avoiding the side effect (the read) in the condition help readability; or did it just duplicate code and add clutter?

It's not OK for a condition to have side effects (if that makes the code less readable) and it is also OK for a condition to have side effects (if that makes the code more readable). The key factor is "readability". Everything else is rules created by fools in a misguided attempt to improve readability (while often having the opposite effect).

Body:
In my world, a read from memory may be considered a side effect (e.g. memory mapped IO).

Now, consider the following:

    while( ( *memory_mapped_device_status_register & READY_FLAG) == 0) {
       // Wait
    }

And compare to:

    status = *memory_mapped_device_status_register;
    while( ( status & READY_FLAG) == 0) {
        // Wait
        status = *memory_mapped_device_status_register;
    }

Did avoiding the side effect (the read) in the condition help readability; or did it just duplicate code and add clutter?

It's not OK for a condition to have side effects (if that makes the code less readable) and it is also OK for a condition to have side effects (if that makes the code more readable). The key factor is "readability". Everything else is rules created by fools in a misguided attempt to improve readability (while often having the opposite effect).


问:
Why did the creators of the Internet Protocol decide to use IP addresses to identify a particular computer?
Why did the creators of the Internet Protocol decide to use IP addresses to identify a particular computer?

Why not just have a unique ID assigned to each computer upon manufacture, then use that ID for identification of the computer?

答:
IP does not identify a computer - one computer can have multiple IPs and a single IP can belong to multiple computers as long as they are in different networks.

IP is not identifier, it's a part of routing. It identifies an endpoint. And it has to be configurable so one computer could be used in different networks - when you change your network you change IP addresses of computers. If these were fixed, you couldn't have the routing mechanism that is used in IP networks.

For example your name could be your (fixed) identifier, but your address is where your mail is delivered to. Address is configurable here - if you move, you get new address and whoever moves to your old place gets your old address. If a street name (network configuration) changes, so does your address. But the delivery mechanism stays the same.


答: But with such unique ID as MAC still there is the problem of locating the device in a network. It's impossible to have all devices to be interconnected and just seek the destination one by one over all hosts in the world. It's the purpose of the invention some hierarchical addresses like IP.</p>

Body:
Why did the creators of the Internet Protocol decide to use IP addresses to identify a particular computer?

Why not just have a unique ID assigned to each computer upon manufacture, then use that ID for identification of the computer?


答:
The MAC address is what identifies a computer, or rather its networking hardware.

What an IP address does is describe where it the hardware is. Routers use it to figure out where to route the packets so they arrive at the correct destination.

As a MAC address does not change when you move the hardware it is in-practical to use for routing, as it would essentially mean that every router in the entire world would need to keep track of the location of each and every MAC-address.
IP addresses work in the manner that each router does not need complete information of the recipient to route them correctly, they know which IP range to send where. This way, only one actual router or switch needs to know which IP is located where exactly. Every other router only needs a very general idea.

Title: Why did the creators of the Internet Protocol decide to use IP addresses to identify a particular computer?


答:
If every computer would have a unique id routing tables would have to include all routes to all devices on the internet. This is impractical.

That's why tcp/ip uses a tiered approach.

If my computer 1.1.1.1 wants to communicate with 2.2.2.2 it basically asks the gateway to forward the packet, so it communicates with: 1.1.1.0, but that gateway also doesn't know where 2.2.2.2 is so it asks his gateway to forward the packet, gateway 1.1.0.0 picks it up and asks 1.0.0.0 . 1.0.0.0 doesn't know where 2.2.2.2 is either, but it does know where 2.0.0.0 is (in his routing table) so the request goes now down because 2.0.0.0 knows where 2.2.0.0 is and forwards the packet, this all the way till the packet reaches 2.2.2.2

(This is an EXTREME oversimplification of what happens and there can be any amount of hops between 1.0.0.0 and 2.0.0.0).

This tiered approach with routing tables makes for efficient locating of another computer in a network. But it also means there has to be a system without the unique ID because routing tables cannot contain all ids and routes of all machines connected to the internet.


问:
What's stopping Oracle from supporting identity (auto-numeric) columns?
EDIT: As gavenkoa's answer points out, Oracle Database 12c (released a couple of years after this question was asked) has support for Identity Columns.

As far as I know, Oracle's RDBMS is one of the few (the only?) SQL database products that doesn't support identity/autonumeric columns.

The alternative offered by Oracle is database sequences, a feature in many ways much more powerful than auto-numeric columns, but not equivalent.

It is not that I don't like sequences. What I hate is having a different programming model for generating row identity values between Oracle and any other database. For example, I often try to setup HSQL or SQLite for java apps that will eventually run over an Oracle database when I'm not working specifically on the data layer (just as a stub or mocking database). I cannot do that easily because I need different set of SQL DDL scripts: one for Oracle, and one for everyone else; I also need two sets of Hibernate mapping files if I'm using Hibernate.

What I find intriguing is that Oracle Database, being one of the most complete and robust enterprise software packages of the last decade hasn't put that seemingly basic feature in their product, but almost any other RDBMS, even the smaller ones, has it.

Why?

Why doesn't oracle support a sequence-based identity column shortcut syntax that dumb and lazy people like me can use?

The only reason I can think of is that Oracle does that on purpose as a vendor lock-in strategy so your code is harder to migrate to other RDBMS where your database sequences cannot be used.

Or maybe I'm just wrong and confused? Please enlighten me.

答:
http://www.oracle-base.com/articles/12c/identity-columns-in-oracle-12cr1.php

The 12c database introduces the ability define an identity clause against a table column defined using a numeric type. The syntax is show below.

```<code>GENERATED
[ ALWAYS | BY DEFAULT [ ON NULL ] ]
AS IDENTITY [ ( identity_options ) ]
</code>```

Body:
http://www.oracle-base.com/articles/12c/identity-columns-in-oracle-12cr1.php

The 12c database introduces the ability define an identity clause against a table column defined using a numeric type. The syntax is show below.

GENERATED
[ ALWAYS | BY DEFAULT [ ON NULL ] ]
AS IDENTITY [ ( identity_options ) ]


答:
The priorities of Oracle are just way different from the once of the everyday developer.

From my experience I'd categorize Oracles attitude as follows:

Top Priority

Reliablity: If one thing makes you look bad in the RDBMS world, it is destroyed data, broken backups and select statements returning wrong data.

Performance: The customers that pay really big bucks (and who cares about the rest?) has huge databases and a lot of work to do. So things that make large databases fast are features that sell themselves

Low or No Priority

Developer usability: If a developer wants to work on something nice and fancy, she left RDBMSes a long time ago. So the rest doesn't mind jumping through hoops for some basic task. They also aquired so much specialized Oracle know how, that switching systems is difficult.

There a lot of thing that fall into this category: tool integration with Version Control systems; management for database migrations; Boolean datatype for table columns; Identity columns.

For all these things and probably many more there are some workarounds / patches that somehow get the job done. As in the case of sequences even more powerful and flexible, but inconvenient. But since almost no paying customer chooses the RDBMS based on its niceness to the developer Oracle doesn't care.

To get an impression of the mindset of Oracle (and of many developers/admins working with or for Oracle) let me quote a piece from Tom Kyte:

You Asked

Here's a real short one for you Tom:

Why doesn't Oracle RDBMS have a boolean datatype?

and we said...

since

```<code>...,
flag char(1) check (flag in ( 'Y', 'N' )),
...,
</code>```

serves the same purpose, requires the same amount of space and does
  the same thing - I  guess we feel this is a feature we can let them
  have that we really don't need.

I mean - what do you get back from a column in "access" that is a
  boolean?  TRUE / FALSE.   We'll give you Y/N -- if you would like
  TRUE/FALSE, we can accomplish that easily with DECODE(flag,'Y','TRUE','N','FALSE')

Which I personally translate to: Who needs types? Assembler is just fine.

Title: What's stopping Oracle from supporting identity (auto-numeric) columns?

Body:
EDIT: As gavenkoa's answer points out, Oracle Database 12c (released a couple of years after this question was asked) has support for Identity Columns.

As far as I know, Oracle's RDBMS is one of the few (the only?) SQL database products that doesn't support identity/autonumeric columns.

The alternative offered by Oracle is database sequences, a feature in many ways much more powerful than auto-numeric columns, but not equivalent.

It is not that I don't like sequences. What I hate is having a different programming model for generating row identity values between Oracle and any other database. For example, I often try to setup HSQL or SQLite for java apps that will eventually run over an Oracle database when I'm not working specifically on the data layer (just as a stub or mocking database). I cannot do that easily because I need different set of SQL DDL scripts: one for Oracle, and one for everyone else; I also need two sets of Hibernate mapping files if I'm using Hibernate.

What I find intriguing is that Oracle Database, being one of the most complete and robust enterprise software packages of the last decade hasn't put that seemingly basic feature in their product, but almost any other RDBMS, even the smaller ones, has it.

Why?

Why doesn't oracle support a sequence-based identity column shortcut syntax that dumb and lazy people like me can use?

The only reason I can think of is that Oracle does that on purpose as a vendor lock-in strategy so your code is harder to migrate to other RDBMS where your database sequences cannot be used.

Or maybe I'm just wrong and confused? Please enlighten me.

Body:
The priorities of Oracle are just way different from the once of the everyday developer.

From my experience I'd categorize Oracles attitude as follows:

Top Priority

Reliablity: If one thing makes you look bad in the RDBMS world, it is destroyed data, broken backups and select statements returning wrong data.

Performance: The customers that pay really big bucks (and who cares about the rest?) has huge databases and a lot of work to do. So things that make large databases fast are features that sell themselves

Low or No Priority

Developer usability: If a developer wants to work on something nice and fancy, she left RDBMSes a long time ago. So the rest doesn't mind jumping through hoops for some basic task. They also aquired so much specialized Oracle know how, that switching systems is difficult.

There a lot of thing that fall into this category: tool integration with Version Control systems; management for database migrations; Boolean datatype for table columns; Identity columns.

For all these things and probably many more there are some workarounds / patches that somehow get the job done. As in the case of sequences even more powerful and flexible, but inconvenient. But since almost no paying customer chooses the RDBMS based on its niceness to the developer Oracle doesn't care.

To get an impression of the mindset of Oracle (and of many developers/admins working with or for Oracle) let me quote a piece from Tom Kyte:

You Asked

Here's a real short one for you Tom:

Why doesn't Oracle RDBMS have a boolean datatype?

and we said...

since

...,
flag char(1) check (flag in ( 'Y', 'N' )),
...,

serves the same purpose, requires the same amount of space and does
  the same thing - I  guess we feel this is a feature we can let them
  have that we really don't need.

I mean - what do you get back from a column in "access" that is a
  boolean?  TRUE / FALSE.   We'll give you Y/N -- if you would like
  TRUE/FALSE, we can accomplish that easily with DECODE(flag,'Y','TRUE','N','FALSE')

Which I personally translate to: Who needs types? Assembler is just fine.


答:
Why did the creators of the Internet Protocol decide to use IP addresses to identify a particular computer?

They didn't. It identifies a network connection, though that same connection could have other IP addresses as well.

Why not just have a unique ID assigned to each computer upon manufacture, then use that ID for identification of the computer?

For one thing they don't ID computers as above.

Okay, say they wanted to do it with network adaptors. They would have had to convince every network adaptor manufacturer to use an identifier from a set controlled by people involved in this particular plan for connecting networks that a lot of people didn't think would work, before it could work. Good luck with that.

Also, these network hardware manufacturers didn't care about TCP/IP, they cared about their own network protocols and perhaps secondarily about those they were competing with. In some cases having a layer on top that made the differences between e.g. ethernet, ALOHAnet, token bus, etc. was a bad thing for some technologies in the long term, because it made some of what they did less useful (TCP/IP could do it instead) and people could eventually move to those that did just what TCP/IP needed and little else (as ethernet did). TCP/IP was a trojan-horse to these companies; happily playing with them, but destroying their business at the same time. Why should they help.

Also, some of these technologies predated TCP/IP, and so they wouldn't be able to interoperate and TCP/IP couldn't have become used on just about all types of network.

Also, which address where? My machine currently has an address of 192.168.1.24 (among others), which is also used by thousands of other machines on other networks. I don't need a unique address because I'm not directly connected to the Internet. With IPv6 we're beginning to move to a point where we could have a genuinely unique id for every machine if we really wanted, but prior to that doing this would have been both limiting in number (four billion would probably have seemed like a lot of devices at the time, but that would require a very tight distribution of numbers, so in practice there'd be many fewer even if that was a realistic concern) and pointless; the whole point of IP isn't networking but inter-networking, so we need only worry about one network at a time when it comes to identifiers, and routers can let those networks internetwork.


答:
One solution I have seen is calling handle_do two times, the first of which returns the size needed to allocate, but doesn't that affect the performance?

Asking about performance like this, is the wrong question to ask. Consider implementing it, deciding on your performance requirements, measuring performance, and if it is indeed a problem, you can consider implementing a workaround.

I have seen the "call API twice, once for parameters for the second call" only in the Windows API. In particular, the choice to call APIs twice like that, is bad for clients (in the Windows API, getting a damn error string, looks like writing half a novel of code). It also breaks SRP.

Ideally, you should optimize your design for the opposite (make client code easier to write, at the expense of the API implementation - if you have to).

Is it a bad practice to allocate or reallocate memory in handle_do?

No.

Does it even matter when using handle types (since the init/free routines are made clear)?

No, it doesn't. You just have to remember when testing it, to check for invalid combinations of APIs (i.e., add tests like calling handle_init, handle_free, handle_do, in this order).

The problem is that the size cannot be always determined in the initialization step and it has to be calculated in handle_do.

Is the size visible in client code? Does this size matter in client code? If the answer to both questions is "no", then the size is just an implementation detail (i.e. it shouldn't matter in client code). If the answer is "yes" to both questions, you should probably add an API for computing this size as a separate operation.

Title: How to abide the "allocate in caller" rule when the size is computed in the callee?

Body:
Let's say we have an opaque type handle_t that is managed through a simple interface with functions such as:

```<code>handle_t *handle_init(void);
int handle_do(handle_t *);
void handle_free(handle_t *);
</code>```

The problem is that the size cannot be always determined in the initialization step and it has to be calculated in handle_do. One solution I have seen is calling handle_do two times, the first of which returns the size needed to allocate, but doesn't that affect the performance?

Is it a bad practice to allocate or reallocate memory in handle_do? Does it even matter when using handle types (since the init/free routines are made clear)?


答:
For the same reason the postal service uses addresses rather than names.

Postal services (and other carriers of packages) don't really ship packages to people. They ship to locations, and let the people at that location sort out which person actually gets the package. The reason they do this is that you can't tell where a person is from his or her name alone, and you can't encode that in the name without making it changeable.

The Internet doesn't use just one protocol: it actually stacks up several protocols, one on top of another. There are protocols which use unique IDs, and they reside in the lowest level, called the link layer. Ethernet (which uses MAC addresses) and PPP (which most commonly uses phone numbers) are two popular examples of link-layer protocols. But the link layer has its limits: you can only get a signal between computers that are directly connected to each other, because everyone already has to know where everyone is. This makes it like the people at the package's destination: everyone knows each other already, so they can sort out between themselves who will actually get the package.

IP resides one step up from this, in the network layer (sometimes called the Internet layer). IP's job is to get a signal between locations that aren't directly connected. Others have already gone into the hierarchical routing scheme that it uses, but most postal services have used similar hierarchical systems since long before the Internet, or even computers. They do this because it's the easiest way to identify different locations and route things between them.

But computers and locations are not the same thing. Computers, like people, can move between different locations: for example, you might move a laptop between your home and your workplace. More than one computer can reside at a given location: if you use a wireless router at home, then you may have several devices connected, but they all share a single IP address as far as the outside world is concerned. It is even possible for a single computer to have more than one address, in certain circumstances.

The Internet needs to be able to handle all of these cases. To do this in a simple and efficient manner, they use addresses rather than IDs. This way, IP doesn't have to know or care what is on each end of the connection: there is only a signal, a place it's coming from, and a place to carry it to. Other protocols in the stack can take care of the other details.


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答:
You can rarely impress people by trying to impress them.  And as long as you try to impress people, and they don't seem impressed, your frustration will grow.

Just do your job in a way that makes you proud of yourself. Don't worry about what anyone thinks. The only person you can make happy is you.


问:
Wrap all external calls with flag to fight against recursion and double-entry?
Producing predictable output for each possible input is the responsibility of each module. For example (in C#):

```<code>class Logger
{
    public ITextWriter Writer { get; set; }

    private uint counter;

    /// <summary>
    /// Writes message in special format and returns the number of total messages written
    /// </summary>
    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));

        return ++counter;
    }
}
</code>```

Logger module is quite verbose, but it's output - exception, call to a depedency and returned value - is predictable and obvious for each argument and state.

But one possible use-case bothers me. What if Writer was set to some weird implementation which somehow calls the Logger.Debug method on that same object? First possible consequence is stackoverflow due to infinite recursion. Second - unpredictable output and possible bugs. It's obvious that such situation must be controlled somehow. If we want predictable output for our logger, it should control double-entries:

```<code>    // ...
    private bool enter;

    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        if (enter) throw new InvalidOperationException("Double-entry");

        enter = true;

        Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));

        enter = false;

        return ++counter;
    }
    // ...
</code>```

And it seems that every external call (a call not to it's own components) must be wrapped with such flags. That looks crazy!

Is it how good code written? Or is it normal to beleive that your system has no circular calls? Am I missing something important? Please, advise.

UPDATE

It's even worse, guys:

```<code>    // ...

    private bool enter;

    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        if (enter) throw new InvalidOperationException("Double-entry");

        try
        {
            enter = true;

            Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));
        }
        finally
        {
            enter = false;
        }

        return ++counter;
    }
    // ...
</code>```

I beleive that catching an exception is on duty of higher-level module (the one which created them all), so exceptions must follow their way. But the state after unsuccessfull call must remain correct. Exception is not the end of the world, and modules possibly can be re-used.

答:
If you use design by contract then you could specify that implementations of ITextWriter should not call Logger.Debug.

Only if it's obvious that some implementation would have a reason to call Logger.Debug would you bother defending against such a case.

A more interesting question would be a multi-threaded situation.  Does the responsibility of handling multi-threaded calls fall to Logger or the implementation of ITextWriter?  Or is your library not handling the case of thread-safety?  (Currently your implementation of Logger is definitely not thread-safe due to your incrementing of the counter member).

As you can see, your code can only handle the "known knowns" so to speak.


答:
The key to understanding the original design of the Internetworking Protocol is that networks already existed, and the plan was to join networks together using existing technology such as DECnet. Requiring people to add new hardware with a unique identifier would have handicapped it, and wasn't required for any technological reason. The system used was to allocate a prefix (such as 8.0.0.0/24) to an organisation, and then make it the responsibility of that organisation to assign addresses within that range.

It also allows the administrator to assign multiple IPs to the same computer (for consolidation of services), or alternatively to replace the computer but continue to use the same IP address, or to use the same IP address on a detached test network, and so on. Tying to particular hardware would be limiting.

Ethernet uses MAC addresses to distinguish between nodes on the same LAN, but Ethernet post-dates the Internet and takes some inspiration from it: http://inventors.about.com/library/weekly/aa111598.htm claims no earlier than 1973, while the first internet RFCs are from 1969 (http://www.ietf.org/download/rfc-index.txt), at roughly the same time as the moon landings.


问:
Correct terminology in type theory: types, type constructors, kinds/sorts and values
In an answer to a previous question, a small debate started about correct terminology for certain constructs. As I did not find a question (other than this or that, which is not quite the right thing) to address this clearly, I am making this new one.

The questionable terms and their relationships are: type, type constructor, type parameter, kinds or sorts, and values.

I also checked Wikipedia for type theory, but that didn't clarify it much either.

So for the sake of having a good reference answer and to check my own understanding:

How are these things defined properly?

What is the difference between each of these things?

How are they related to each other?

答:
How are these things defined properly?

They are properly defined by rigid, academic mathematical backing, providing strong assertions as to what they are, how they work, and what is guaranteed.

But programmers largely don't need to know that. They need to understand the concepts.

Values

Let's start with values, since everything builds from there. Values are the data used in computing. Depending on the approach, they're the values that everyone is familiar with: 42, 3.14, "How now brown cow", the personnel record for Jenny down in Accounting, etc.

Other interpretations of values are symbols. Most programmers understand these symbols to be the "values" of an enumeration. Left and Right are symbols for the enum Handedness (ignoring ambidextrous people and fish).

Regardless of the implementation, values are the different things that the language works with to perform calculations.

Types

The problem with values is that not all calculations are legal for all values. 42 + goat doesn't really make sense.

This is where types come into play. Types are metadata that define subsets of values. The Handedness enum above is a good example. This type says "only Left and Right may be used here". This allows programs to determine very early that certain operations will result in error.

Another practical use to consider is that under the hood, computers work with bytes. The byte 42 might mean the number 42, or it might mean the character *, or it might mean Jenny from Accounting. Types also (in practical use, not theoretical so much) help define the encoding for the underlying collection of bytes used by computers.

Kinds

And here's where we start going a little out there. So, when a programming language has a variable that refers to a type, what type does it have?

In Java and C# for example, it has the type Type (which has the type Type, which has... and so on all the way down). This is the concept behind kinds. In some languages, you can do a bit more useful things with a Type variable than Java and C#. Once that happens it becomes useful to say "I want a value that is a Type, but is also some kind of IEnumerable<int>". Ta-da! Kinds.

Most programmers can think of kinds like Java and C# generic constraints. Consider public class Foo<T> where T: IComparable{}. In a language with kinds, the T: kindOf(IComparable) variable declaration becomes legal; not just a special thing you can do in class and function declarations.

Type Constructors

Perhaps unsurprisingly, type constructors are simply constructors for types. "But how do you construct a type? Types just are.". Eh... not so much.

Also unsurprisingly, it's pretty difficult to build all of the different useful subsets of values any computer program will ever use. Type constructors work to help allow programmers to "build" those subsets in meaningful ways.

The most ubiquitous example of a type constructor is an array definition: int[4]. Here you're specifying 4 to the type constructor, which uses the value to build you an array of ints with 4 entries. If you specified a different input type, you'd get a different output type.

Generics are another form of type constructor, taking another type as their input.

In many languages there is a type constructor like P -> R to build a type that represents a function that takes type P and returns type R.

Now, the context will determine if a "function that returns a type" is a type constructor or not. In my (admittedly limited) experience, the line is "can you use this type at compile time?". Yes? Type constructor. No? Just a function.

Type Parameter

So you remember the parameters passed to Type Constructors? They're commonly known as Type Parameters, since the common form of a Type Constructor is Type[param] or Type<param>.

ContentLicense: CC BY-SA 4.0


答:
Alright, let's go one by one.

Values

Values are the concrete pieces of data that programs evaluate and juggle. Nothing fancy, some examples might be

1

true

"fizz buzz foo bar"

Types

A nice description for a type is "a classifier for a value". A type is a little bit of information about what that value will be at runtime, but indicated at compile time.

For example if you tell me that e : bool at compile time, and I'll know that e is either true or false during runtime, nothing else! Because types classify values nicely like this, we can use this information to determine some basic properties of your program.

For example, if I ever see you adding e and e' when e : int and e' : String, then I know something is a bit off! In fact I can flag this and throw an error at compile time, saying "Hey, that doesn't make any sense at all!".

A more powerful type system allows for more interesting types which classify more interesting values. For example, let's consider some function

```<code>f = fun x -> x
</code>```

It's pretty clear that f : Something -> Something, but what should that Something be? In a boring type system, we'd have to specify something arbitrary, like Something = int. In a more flexible type system, we could say

```<code>f : forall a. a -> a
</code>```

That is to say "for any a, f maps an a to an a". This let's us use f more generally and write more interesting programs.

Moreover, the compiler is going to check actually satisfying the classifier we've given it, if f = fun x -> true then we have a bug and the compiler will say so!

So as a tldr; a type is a compile time constraint on the values an expression can be at runtime.

Type Constructor

Some types are related. For example a list of integers is very similar to a list of strings. This is almost like how sort for integers is almost like sort for strings. We can imagine a sort of factory that builds these almost-the-same types by generalizing over their differences and building them upon demand. That's what a type constructor is. It's kind of like a function from types to types, but a little more limited.

The classic example is a generic list. A type constructor for is just the generic definition

```<code> data List a = Cons a (List a) | Nil
</code>```

Now List is a function which maps a type a to a list of values of that type! In Java-land I think these are perhaps called "generic classes"

Type Parameters

A type parameter is just the type passed to a type constructor (or function). Just like in the value level we'd say foo(a) has a parameter a just like how List a has a type parameter a.

Kinds

Kinds are a bit tricky. The basic idea is that certain types are similar. For example, we have all the primitive types in java int, char, float... which all behave as if they have the same "type". Except, when we're speaking of the classifiers for types themselves, we call the classifiers kinds. So int : Prim, String : Box, List : Boxed -> Boxed.

This system gives nice concrete rules about what sort of types we can use where, just like how types govern values. It'd clearly be nonsense to say

```<code> List<List>
</code>```

or

```<code> List<int>
</code>```

In Java since List needs to be applied to a concrete type to be used like that! If we look at their kinds List : Boxed -> Boxed and since Boxed -> Boxed /= Boxed, the above is a kind error!

Most of the time we don't really think about kinds and just treat them as "common sense", but with fancier type systems it's something important to think about.

A little illustration of what I've been saying so far

```<code> value   : type : kind  : ...
 true    : bool : Prim  : ...
 new F() : Foo  : Boxed : ...
</code>```

Better Reading Than Wikipedia

If you're interested in this sort of thing, I'd highly recommend investing a good textbook. Type theory and PLT in general is pretty vast and without a coherent base of knowledge you (or at least I) can wander around without getting anywhere for months.

Two of my favorite books are

Types and Programming Language - Ben Pierce

Practical Foundations of Programming Languages - Bob Harper

Both are excellent books that introduce what I've just talked about and much more in beautiful, well explained detail.

Title: Correct terminology in type theory: types, type constructors, kinds/sorts and values

Body:
In an answer to a previous question, a small debate started about correct terminology for certain constructs. As I did not find a question (other than this or that, which is not quite the right thing) to address this clearly, I am making this new one.

The questionable terms and their relationships are: type, type constructor, type parameter, kinds or sorts, and values.

I also checked Wikipedia for type theory, but that didn't clarify it much either.

So for the sake of having a good reference answer and to check my own understanding:

How are these things defined properly?

What is the difference between each of these things?

How are they related to each other?

Body:
Alright, let's go one by one.

Values

Values are the concrete pieces of data that programs evaluate and juggle. Nothing fancy, some examples might be

1

true

"fizz buzz foo bar"

Types

A nice description for a type is "a classifier for a value". A type is a little bit of information about what that value will be at runtime, but indicated at compile time.

For example if you tell me that e : bool at compile time, and I'll know that e is either true or false during runtime, nothing else! Because types classify values nicely like this, we can use this information to determine some basic properties of your program.

For example, if I ever see you adding e and e' when e : int and e' : String, then I know something is a bit off! In fact I can flag this and throw an error at compile time, saying "Hey, that doesn't make any sense at all!".

A more powerful type system allows for more interesting types which classify more interesting values. For example, let's consider some function

f = fun x -> x

It's pretty clear that f : Something -> Something, but what should that Something be? In a boring type system, we'd have to specify something arbitrary, like Something = int. In a more flexible type system, we could say

f : forall a. a -> a

That is to say "for any a, f maps an a to an a". This let's us use f more generally and write more interesting programs.

Moreover, the compiler is going to check actually satisfying the classifier we've given it, if f = fun x -> true then we have a bug and the compiler will say so!

So as a tldr; a type is a compile time constraint on the values an expression can be at runtime.

Type Constructor

Some types are related. For example a list of integers is very similar to a list of strings. This is almost like how sort for integers is almost like sort for strings. We can imagine a sort of factory that builds these almost-the-same types by generalizing over their differences and building them upon demand. That's what a type constructor is. It's kind of like a function from types to types, but a little more limited.

The classic example is a generic list. A type constructor for is just the generic definition

 data List a = Cons a (List a) | Nil

Now List is a function which maps a type a to a list of values of that type! In Java-land I think these are perhaps called "generic classes"

Type Parameters

A type parameter is just the type passed to a type constructor (or function). Just like in the value level we'd say foo(a) has a parameter a just like how List a has a type parameter a.

Kinds

Kinds are a bit tricky. The basic idea is that certain types are similar. For example, we have all the primitive types in java int, char, float... which all behave as if they have the same "type". Except, when we're speaking of the classifiers for types themselves, we call the classifiers kinds. So int : Prim, String : Box, List : Boxed -> Boxed.

This system gives nice concrete rules about what sort of types we can use where, just like how types govern values. It'd clearly be nonsense to say

 List<List>

or

 List<int>

In Java since List needs to be applied to a concrete type to be used like that! If we look at their kinds List : Boxed -> Boxed and since Boxed -> Boxed /= Boxed, the above is a kind error!

Most of the time we don't really think about kinds and just treat them as "common sense", but with fancier type systems it's something important to think about.

A little illustration of what I've been saying so far

 value   : type : kind  : ...
 true    : bool : Prim  : ...
 new F() : Foo  : Boxed : ...

Better Reading Than Wikipedia

If you're interested in this sort of thing, I'd highly recommend investing a good textbook. Type theory and PLT in general is pretty vast and without a coherent base of knowledge you (or at least I) can wander around without getting anywhere for months.

Two of my favorite books are

Types and Programming Language - Ben Pierce

Practical Foundations of Programming Languages - Bob Harper

Both are excellent books that introduce what I've just talked about and much more in beautiful, well explained detail.


问:
What is your code review and approval process, and what are its advantages/disadvantages?
Does your team rely on code reviews for approval of work? Is it simply QA that signs off your features and fixes? Do you have a lead programmer (or architect) that reviews code design and implementation?

Or is it simply a Works on My Machine paradigm?

What would you recommend or have seen that works well?

答:
Code reviews can be immensely helpful in identifying potential bugs and making sure that developers adhere to company coding standards. However, it's important to have clear guidelines about what is and is not up for review. A written coding standard—accessible via a web browser—is a must, in my opinion. And everyone on the team should be given a chance to provide input as to what goes in the standard. When a reviewer flags a defect, he should cite the section of the standard that the code violates, and provide a hyperlink to it.

Having a written standard and requiring that reviewers cite it for each item they mark as a defect has a couple of important effects:

It keeps reviews from getting too personal. Reviewers are merely checking for compliance with an agreed-upon standard, not 'bashing' the developer whose code is under review.

Developers can review code much more quickly when they have a 'checklist' of things to look out for.

I once worked for a company that decided to implement a work flow that used Gerrit for code reviews, and required a review before code could be committed to the dev branch—a decision I was strongly in favor of at the time. And I still am. Unfortunately, we didn't have a written coding standard. A handful of senior team members thought that this would be "overkill", or "too restrictive", and felt that a de facto standard existed within the company culture that "everybody already knows".  Predictably, reviews devolved into an endless debate about whitespace and curly brace placement, and heated discussions regularly occurred on topics that had nothing to do, really, with code quality or executing the company's mission.

So that's the best advice I can give: have a written, web-accessible coding standard (like this one), and require that reviewers stick to it scrupulously when flagging defects. Many software developers tend to have OCD tendencies (I suspect that's what makes us good at coding), and if you don't tamp down on this in code reviews, they can become a bully pulpit for those that can't stand this:

```<code>if (!initialized_) {
    initObject(obj);
}
</code>```

so they keep trying to sway people to do this instead:

```<code>if ( ! initialized_ )
{
    initObject( obj );
}
</code>```

Distinctions like this almost entirely devoid of meaning, and are never a determining factor in the success or failure of a project/company. So either leave brace placement explicitly unspecified in the standard, or just pick something and require everybody to live with it. Better still, use something like uncrustify in a commit hook to enforce a 'standard' syntax. A different company I worked for did that, and I thought it was weird at the time, but I totally get it now. Anything is better than having developers waste money endlessly debating trivialities. We can do that over lunch. (And we're going to, anyway. It's like a sport for us.)

If you have a published standard that 'hits the high spots', I think the dev team itself can handle code reviews. That's how we do it in my current job. (We use Crucible, FWIW, and like it pretty well.) QA isn't involved in the review process at all. A developer who wants to merge his code simply creates a review and invites other developers to join. He has a green light to merge when everyone has finished the review and all defects have been addressed. There's no strict enforcement. You 'should' create a code review before merging your topic branch—and almost everyone does—but circumstances occasionally call for a 'rogue' merge. For our team of 25+ engineers, this has worked out pretty well.

OwnerDisplayName: Edward A

Body:
Code reviews can be immensely helpful in identifying potential bugs and making sure that developers adhere to company coding standards. However, it's important to have clear guidelines about what is and is not up for review. A written coding standard—accessible via a web browser—is a must, in my opinion. And everyone on the team should be given a chance to provide input as to what goes in the standard. When a reviewer flags a defect, he should cite the section of the standard that the code violates, and provide a hyperlink to it.

Having a written standard and requiring that reviewers cite it for each item they mark as a defect has a couple of important effects:

It keeps reviews from getting too personal. Reviewers are merely checking for compliance with an agreed-upon standard, not 'bashing' the developer whose code is under review.

Developers can review code much more quickly when they have a 'checklist' of things to look out for.

I once worked for a company that decided to implement a work flow that used Gerrit for code reviews, and required a review before code could be committed to the dev branch—a decision I was strongly in favor of at the time. And I still am. Unfortunately, we didn't have a written coding standard. A handful of senior team members thought that this would be "overkill", or "too restrictive", and felt that a de facto standard existed within the company culture that "everybody already knows".  Predictably, reviews devolved into an endless debate about whitespace and curly brace placement, and heated discussions regularly occurred on topics that had nothing to do, really, with code quality or executing the company's mission.

So that's the best advice I can give: have a written, web-accessible coding standard (like this one), and require that reviewers stick to it scrupulously when flagging defects. Many software developers tend to have OCD tendencies (I suspect that's what makes us good at coding), and if you don't tamp down on this in code reviews, they can become a bully pulpit for those that can't stand this:

if (!initialized_) {
    initObject(obj);
}

so they keep trying to sway people to do this instead:

if ( ! initialized_ )
{
    initObject( obj );
}

Distinctions like this almost entirely devoid of meaning, and are never a determining factor in the success or failure of a project/company. So either leave brace placement explicitly unspecified in the standard, or just pick something and require everybody to live with it. Better still, use something like uncrustify in a commit hook to enforce a 'standard' syntax. A different company I worked for did that, and I thought it was weird at the time, but I totally get it now. Anything is better than having developers waste money endlessly debating trivialities. We can do that over lunch. (And we're going to, anyway. It's like a sport for us.)

If you have a published standard that 'hits the high spots', I think the dev team itself can handle code reviews. That's how we do it in my current job. (We use Crucible, FWIW, and like it pretty well.) QA isn't involved in the review process at all. A developer who wants to merge his code simply creates a review and invites other developers to join. He has a green light to merge when everyone has finished the review and all defects have been addressed. There's no strict enforcement. You 'should' create a code review before merging your topic branch—and almost everyone does—but circumstances occasionally call for a 'rogue' merge. For our team of 25+ engineers, this has worked out pretty well.


问:
What is convention based framework?
I'm reading about ColdBox, and I came across this word.

So what is meant by convention based framework?

答:
It means that details that usually do not carry any semantic (that is, any meaning) are used by the framework to generate a default configuration. It is also known as "convention over configuration".

For example, in Ruby on Rails, if you use a class named Customer, the generated database table will automatically be named "customers".

Title: What is convention based framework?


答:
And it seems that every external call (a call not to it's own components) must be wrapped with such flags. That looks crazy!
  Is it how good code written? Or is it normal to beleive that your system has no circular > calls? Am I missing something important? Please, advise.

Levelization.

Levelization will be a key concept for a long time to come. The idea is for pieces of code or components to be separated into levels according to what they focus on doing. I suggest the OP think about levels of methods: higher methods will only call lower ones. Conversely, if authors take a shortcut by writing fewer methods that are all peers, they need high-maintenance guard logic and they start to become ludicrously spaghetti- like. Levelization scales well. Future users: search for it

Here's a recent Google result:

http://blog.coverity.com/2014/01/24/software-complexity-and-levelization/

Title: Wrap all external calls with flag to fight against recursion and double-entry?

Body:
Producing predictable output for each possible input is the responsibility of each module. For example (in C#):

```<code>class Logger
{
    public ITextWriter Writer { get; set; }

    private uint counter;

    /// <summary>
    /// Writes message in special format and returns the number of total messages written
    /// </summary>
    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));

        return ++counter;
    }
}
</code>```

Logger module is quite verbose, but it's output - exception, call to a depedency and returned value - is predictable and obvious for each argument and state.

But one possible use-case bothers me. What if Writer was set to some weird implementation which somehow calls the Logger.Debug method on that same object? First possible consequence is stackoverflow due to infinite recursion. Second - unpredictable output and possible bugs. It's obvious that such situation must be controlled somehow. If we want predictable output for our logger, it should control double-entries:

```<code>    // ...
    private bool enter;

    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        if (enter) throw new InvalidOperationException("Double-entry");

        enter = true;

        Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));

        enter = false;

        return ++counter;
    }
    // ...
</code>```

And it seems that every external call (a call not to it's own components) must be wrapped with such flags. That looks crazy!

Is it how good code written? Or is it normal to beleive that your system has no circular calls? Am I missing something important? Please, advise.

UPDATE

It's even worse, guys:

```<code>    // ...

    private bool enter;

    public uint Debug(string message)
    {
        if (message == null) throw new ArgumentNullException("message");

        if (Writer == null) throw new InvalidOperationException("Writer not set");

        if (enter) throw new InvalidOperationException("Double-entry");

        try
        {
            enter = true;

            Writer.Write(string.Format("{0:HHmmss}: [DEBUG] {1}", DateTime.Now, message));
        }
        finally
        {
            enter = false;
        }

        return ++counter;
    }
    // ...
</code>```

I beleive that catching an exception is on duty of higher-level module (the one which created them all), so exceptions must follow their way. But the state after unsuccessfull call must remain correct. Exception is not the end of the world, and modules possibly can be re-used.


答:
In general you do something sane, and then at some point incorrect use of your library becomes the programmer's problem.

For example for logging you can look at http://logging.apache.org/log4net/index.html.  The writer there is customizable by what level the log is writing at.  And then you simply don't have your debug output using a writer that is itself using the logging framework to do debugging.  Unless you want to, in which case the writer should guard against infinite recursion by looking at the logging level and then deciding whether it wishes to issue a potentially problematic debug statement.

That is a good enough solution.  Any writer should either document itself as not suitable for use with debugging level, or should have that guard to not try to debug itself when so used.