问:
Is it wrong to use Agile when clients' requirements don't change at all?
I have seen a lot of posts recently saying that one of the major reasons why Agile is used is because clients often change the requirements.

However, let's say the clients do not change the requirements often.
In fact, the clients have firm requirements though might be a bit vague (but nothing unreasonably vague), but I use Agile anyway.

The reason why I employ Agile is because the software is complex enough that there are details, problems that I wouldn't recognize until I actually face them.
I could do a full scale heavy planning approach like waterfall, but then it would take a few months to finalize all the high level design and low level coding signatures. There is a very specific, fixed architectural design for the system though.

My question is: Would this be considered as bad, cowboy coding, anti-pattern, etc..?
Must we employ waterfall and plan as much as possible in great details before we start coding when requirements are stable instead of this 'let's do it' mentality in Agile?

EDIT: The major point here is that: we CANNOT blame the clients for changing requirements. Assume the clients pointed us to a very concrete problem, give us a wish list in very reasonable details and leave us alone (ie the clients have their own productive things to do, don't bug them any more. Only demo to them near the end when you have a minimum working prototype). Would it be wrong to use Agile in this scenario?

答:
Agile is ideal if you need a frequent feedback loop with the client. This can be because the requirements change frequently, but it could also be for other reasons.

On the other hand, Agile can work equally well if the requirements are fully stable and the client expects only a single big-bang delivery, but you might have to adapt things a bit for the amount of involvement that the client expects to have during the project. This means that the Product Owner role must be filled from within your own organization and that person must have enough mandate from the customer to make decisions.


答:
Would this be considered as bad, cowboy coding, anti-pattern.

Short answer: no. Doing "agile" correctly does not mean "no planning", it does mean not to overanalyse things.

one of the major reasons why Agile is used is because clients often change the requirements.

That's an oversimplifying statement. "Changing requirements" is also about how the team's understanding of the requirements change. And it is about how the customer's priorities about the requirement change when he actually sees a few releases of the software.

In fact, "agile" works IMHO best exactly in the situation you describe - the client has a good knowledge about his overall requirements, you can write a general plan from it, fill your backlog with lots of "user stories", and have already enough information to choose the right system architecture. The short iterations of an agile development strategy then will help to make the "vague requirements" more precise, with lots of feedback if you are still going into the right direction. It will also give you early feedback about the real effort and costs (which is something you can still fail in a waterfall approach, even if you know every single bit of requirement in detail).

ContentLicense: CC BY-SA 3.0

Title: Is it wrong to use Agile when clients' requirements don't change at all?

Body:
I have seen a lot of posts recently saying that one of the major reasons why Agile is used is because clients often change the requirements.

However, let's say the clients do not change the requirements often.
In fact, the clients have firm requirements though might be a bit vague (but nothing unreasonably vague), but I use Agile anyway.

The reason why I employ Agile is because the software is complex enough that there are details, problems that I wouldn't recognize until I actually face them.
I could do a full scale heavy planning approach like waterfall, but then it would take a few months to finalize all the high level design and low level coding signatures. There is a very specific, fixed architectural design for the system though.

My question is: Would this be considered as bad, cowboy coding, anti-pattern, etc..?
Must we employ waterfall and plan as much as possible in great details before we start coding when requirements are stable instead of this 'let's do it' mentality in Agile?

EDIT: The major point here is that: we CANNOT blame the clients for changing requirements. Assume the clients pointed us to a very concrete problem, give us a wish list in very reasonable details and leave us alone (ie the clients have their own productive things to do, don't bug them any more. Only demo to them near the end when you have a minimum working prototype). Would it be wrong to use Agile in this scenario?


问:
What are the bytes between the MSB and LSB named?
I've searched around and can't find anything on what the middle bytes of a >16-bit integer are called, if anything. Are there standard names for these bytes?

E.g. the number 0x0D0C0B0A would have:

```<code>MSB ??? ??? LSB
 0D  0C  0B  0A
</code>```

答: I guess once MSB determines the order, I call them byte 0, byte 1, byte 2, and then either byte 3 or else MSB.</p>


答:
You can always split the big release into smaller releases(sprints) and ask your client for feedback. This way you are sure that you're doing the right thing and the client can keep track of your progress.

If there is something wrong, you can offer your client the chance to correct you sooner, which is very good. It is better to correct your mistakes as soon as possible, rather than show him a bullshit at the end and try to fix it when you don't even know where to start.


问:
Is WCF strictly an asynchonous comms platform?
Since I last had to do any comms/network programming, the field has exploded with acronyms. In fact, networking almost feels like it is now described by a whole new language.

The very name "Windows Communication Foundation" suggests it should be all things to all people... but I need to be sure I can program up some synchronous real-time* comms on a dedicated gigabit ethernet network. Can someone confirm that WCF is not a starter for this task... or if it is, which of the many confusing acronyms I should get familiar with?

* By real-time, I mean I need to reduce latencies down to an acceptably low level. For our application, which involves transmitting results of video & audio analyses continuously every few milliseconds,  I need to ensure 99% or better of those analyses are presented at the UI within (ideally) 0.5 seconds so that the user has time to respond before the originating network node deletes data out of its buffer to make way for subsequent analyses.

答:
Basically, WCF is intended for asynchronous communications, and I won't be surprised to learn that at a certain level, everything it does it asynchronous.

This being said, you can do blocking operations with WCF, so yes, synchronous real-time communications can use WCF under the hood, given that WCF provides you some interesting aspects such as the fact that it can guarantee that messages will be delivered, and will be in the order they were sent.

The ability to use blocking operations includes even the WCF's web sockets, by the way.

Why would you block the thread until you receive a reply from a distant machine is a different subject. Think twice, since it you probably don't want to freeze your entire application definitively if the network goes down.

One of the uses I've found for blocking operations is to have a proxy class which communicates through WCF under the hood. In this case, when you access someObject.Products, you don't have to know that products are loaded through WCF. It's a powerful abstraction, but also a leaky one: if the distant machine goes down during the operation, you certainly have to know what happens when you call Products property.


问:
Can all the recursive functions be coded with iterations?
What are the advantages of recursion?

Some programming languages can optimize tail recursion, but, still in general terms, recursion consume more resources than regular loops.

Is it possible to have an iterative version of some recursive function?

答:
What are the advantages of recursion?

Simplicity. Without tail-call optimization it of course takes more resources (stack), but how would you implement, say, deltree in Java without recursion? The twist is that delete() can delete directories only if they're empty; here's it with recursion:

```<code>deltree(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File subFileOrDirectory : fileOrDirectory.listFiles()) {
            deltree(subFileOrDirectory);
        }
    }
    fileOrDirectory.delete();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What are the advantages of recursion?

Simplicity. Without tail-call optimization it of course takes more resources (stack), but how would you implement, say, deltree in Java without recursion? The twist is that delete() can delete directories only if they're empty; here's it with recursion:

deltree(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File subFileOrDirectory : fileOrDirectory.listFiles()) {
            deltree(subFileOrDirectory);
        }
    }
    fileOrDirectory.delete();
}


问:
Project is nearly done, but procedural spaghetti code. Do I rewrite or just keep trying to ship it?
I'm a beginner web developer (one year of experience).

A couple of weeks after graduating, I got offered a job to build a web application for a company whose owner is not much of a tech guy. He recruited me to avoid theft of his idea, the high cost of development charged by a service company, and to have someone young he can trust onboard to maintain the project for the long run (I came to these conclusions by myself long after being hired).

Cocky as I was back then, with a diploma in computer science, I accepted the offer thinking I can build anything.

I was calling the shots. After some research I settled on PHP, and started with plain PHP, no objects, just ugly procedural code. Two months later, everything was getting messy, and it was hard to make any progress. The web application is huge. So I decided to check out an MVC framework that would make my life easier. That's where I stumbled upon the cool kid in the PHP community: Laravel. I loved it, it was easy to learn, and I started coding right away. My code looked cleaner, more organized. It looked very good.

But again the web application was huge. The company was pressuring me to deliver the first version, which they wanted to deploy, obviously, and start seeking customers.

Because Laravel was fun to work with, it made me remember why I chose this industry in the first place - something I forgot while stuck in the shitty education system.

So I started working on small projects at night, reading about methodologies and best practice. I revisited OOP, moved on to object-oriented design and analysis, and read Uncle Bob's book Clean Code.

This helped me realize that I really knew nothing. I did not know how to build software THE RIGHT WAY. But at this point it was too late, and now I'm almost done. My code is not clean at all, just spaghetti code, a real pain to fix a bug, all the logic is in the controllers, and there is little object oriented design.

I'm having this persistent thought that I have to rewrite the whole project. However, I can't do it... They keep asking when is it going to be all done.

I can not imagine this code deployed on a server. Plus I still know nothing about code efficiency and the web application's performance.

On one hand, the company is waiting for the product and can not wait anymore. On the other hand I can't see myself going any further with the actual code. I could finish up, wrap it up and deploy, but god only knows what might happen when people start using it.

Do I rewrite, or just keep trying to ship, or is there another option that I've missed?

答:
You're doing good.

You say that your code works, and it's almost ready to ship, right?
And you perceive that your code may be vastly improved. Good.

Your dilemma much reminds me of my first experience with freelancing (getting hired while in my 2nd year at uni to create a multilingual POS system).
I went through endless questioning as I was never satisfied with the code, wanted scalability, wanted to reinvent better wheels... But I just delayed the project (like, by 12 months approximately) and... what? Once you deploy the thing it still needs a lot of proofing, testing, patching etc...

Do you have experience working with professional code-bases? Many code-bases are full of quirky, hard to maintain code. An alternative to discovering the complexity of software by trying to build a large program yourself would be maintaining/extending equally messy code written by other people.

The only cases where I've seen complete rewrites do much good is when the team concurrently adopted a new toolchain/framework.

If the underlying logic (what the program does, not how it is laid out as functions, classes and so forth...) is sound, it will work just as good, so, you thinking that it's spaghetti code doesn't mean it shouldn't be deployed.

You need to let your customer have something that they can use. Then when they ask you to improve it / add functionality you decide whether a refactor is necessary, and it's okay to let your customer know that "some technical work is needed to integrate said new feature". By which they will understand that it will cost them more money, and they will have to wait longer. And they will understand (or you can pull out).

A better time to rewrite everything would be when another customer ask you to create something similar.

In short, unless you can demonstrate that the whole thing will blow in everybody's face if it gets deployed, delaying deployment would be unprofessional, and will not benefit either you or your customer. Learning to do small refactors while fixing bugs or adding new features, that will be valuable experience for you.


问:
How are OOP "objects" and "classes" organized in memory in terms of assembly language?
How are objects organized in memory?

For instance, I know that a function is a piece of code in memory, that expects parameters via the stack and/or the registers and handles it's own stack frame.

But objects are a much more complicated structure. How are they organized?
Does each object have "links" to methods and passes address to itself to that method?

It would be great to see a good explanation of this topic.

UPD. I made the question more exact, and I'm mainly interested in statically typing languages.

答:
If there is no dynamic dispatch (polymorphism), "methods" are just sugary functions, perhaps with an implicit additional parameter. Accordingly, instances of classes with no polymorphic behavior are essentially C structs for the purpose of code generation.

For classical dynamic dispatch in a static type system, there is basically one predominant strategy: vtables. Every instance gets one additional pointer that refers to (a limited representation of) its type, most importantly the vtable: An array of function pointers, one per method. Since the the full set of methods for every type (in the inheritance chain) is known at compile time, one can assign consecutive indices (0..N for N methods) to the methods and invoke the methods by looking up the function pointer in the vtable using this index (again passing the instance reference as additional parameter).

For more dynamic class-based languages, typically classes themselves are first-class objects and each object instead has a reference to its class object. The class object, in turn, owns the methods in some language-dependent manner (in Ruby, methods are a core part of the object model, in Python they're just function objects with tiny wrappers around them). The classes typically store references to their superclass(es) as well, and delegate the search for inherited methods to those classes to aid metaprogramming which adds and alters methods.

There are many other systems that aren't based on classes, but they differ significantly, so I'll only pick out one interesting design alternative: When you can add new (sets of) methods to all types at will anywhere in the program (e.g. type classes in Haskell and traits in Rust), the full set of methods isn't known while compiling. To resolve this, one creates a vtable per trait and passes them around when the trait implementation is required. That is, code like this:

```<code>void needs_a_trait(SomeTrait &x) { x.method2(1); }
ConcreteType x = ...;
needs_a_trait(x);
</code>```

is compiled down to this:

```<code>functionpointer SomeTrait_ConcreteType_vtable[] = { &method1, &method2, ... };
void needs_a_trait(void *x, functionpointer vtable[]) { vtable[1](x, 1); }
ConcreteType x = ...;
needs_a_trait(x, SomeTrait_ConcreteType_vtable);
</code>```

This also means the vtable information isn't embedded in the object. If you want references to an "instance of a trait" that will behave correctly when, for example, stored in data structures that contain many different types, one can create a fat pointer (instance_pointer, trait_vtable). This is actually a generalization of the above strategy.

Body:
If there is no dynamic dispatch (polymorphism), "methods" are just sugary functions, perhaps with an implicit additional parameter. Accordingly, instances of classes with no polymorphic behavior are essentially C structs for the purpose of code generation.

For classical dynamic dispatch in a static type system, there is basically one predominant strategy: vtables. Every instance gets one additional pointer that refers to (a limited representation of) its type, most importantly the vtable: An array of function pointers, one per method. Since the the full set of methods for every type (in the inheritance chain) is known at compile time, one can assign consecutive indices (0..N for N methods) to the methods and invoke the methods by looking up the function pointer in the vtable using this index (again passing the instance reference as additional parameter).

For more dynamic class-based languages, typically classes themselves are first-class objects and each object instead has a reference to its class object. The class object, in turn, owns the methods in some language-dependent manner (in Ruby, methods are a core part of the object model, in Python they're just function objects with tiny wrappers around them). The classes typically store references to their superclass(es) as well, and delegate the search for inherited methods to those classes to aid metaprogramming which adds and alters methods.

There are many other systems that aren't based on classes, but they differ significantly, so I'll only pick out one interesting design alternative: When you can add new (sets of) methods to all types at will anywhere in the program (e.g. type classes in Haskell and traits in Rust), the full set of methods isn't known while compiling. To resolve this, one creates a vtable per trait and passes them around when the trait implementation is required. That is, code like this:

void needs_a_trait(SomeTrait &x) { x.method2(1); }
ConcreteType x = ...;
needs_a_trait(x);

is compiled down to this:

functionpointer SomeTrait_ConcreteType_vtable[] = { &method1, &method2, ... };
void needs_a_trait(void *x, functionpointer vtable[]) { vtable[1](x, 1); }
ConcreteType x = ...;
needs_a_trait(x, SomeTrait_ConcreteType_vtable);

This also means the vtable information isn't embedded in the object. If you want references to an "instance of a trait" that will behave correctly when, for example, stored in data structures that contain many different types, one can create a fat pointer (instance_pointer, trait_vtable). This is actually a generalization of the above strategy.


问:
More requirements in a single use case - correct?
I have been arguying with a developer who insists that 1 functional request (FR) == 1 use case (UC). I think that is nonsense as there are requirements often describing situations arising from the same point - for this the use cases have alternate flows.

For example:

```<code>FR01 - User can log in
FR02 - User's account will be locked after 3 incorrect passwords.
FR03 - Logged user can log out
</code>```

I believe all these can be nicely captured within a single use case, describing the interaction between the user and the system.

But maybe I am missing something?

EDIT: According to the book "Use Case Modeling" from Bittner, Spence:

a use case contains a set of description of requirements, the requirements
  are presented in the form of narrative rather than  an itemized list...

...

So I would say definitely more requirements can be captured within a single use case.

答:
A use case describes an independent, complete interaction done by the user. Think about what the user will be doing.

A use case is descriptive. It describes the motivation of the user, what purpose the feature serves, why the feature is important, etc. It does not have the "hard" functional requirements used in a PRD. But it describes the same scenario with more context.

Then break that down into "hard" functional requirements. Based on your examples, I think you are mixing the two scopes. Assume the example of a shopping website:

UC 1: As a customer, I want to log in to the site so that I can save relevant data to my profile. This helps me to save time and effort by entering the data only once. I want my data to be secure and visible only to me.

FR 1.1: If user is already logged in, they should not be able to log in again

FR 1.2: If not logged in. a login screen should be shown

FR 1.3: If login is successful, ...

FR 1.4: If login is unsuccessful, show an error message.

FR 1.5: User's account will be locked after 3 incorrect passwords

and so on.


答:
What are the advantages of recursion?

Try solving the Towers of Hanoi problem iteratively.  Once you give up, take a look at the iterative solution and compare it to the recursive one.  Which one is simpler?

Is it possible to have an iterative version of some recursive function?

Yes, in principle.  However for many problems, including very common tasks, such as tree traversals, the recursive solutions are much simpler and more elegant than the iterative ones.

Title: Can all the recursive functions be coded with iterations?

Body:
What are the advantages of recursion?

Some programming languages can optimize tail recursion, but, still in general terms, recursion consume more resources than regular loops.

Is it possible to have an iterative version of some recursive function?


问:
Passing notifications between programs written in different programming languages
I work in a team of people with experience in varied programming languages. Recently we were required to build a report when an order is placed in our system. Our ecommerce store runs on PHP and the program to send the report was written in Java. The major challenge we faced was setting up a way so that the Java process is triggered as soon as the order placed. In the same vein, we have plenty of programs written in Python, Scala etc that need to be coordinated and be aware of when to do a task X when task Y happens.

As of now, our go to solutions to this problem is to setup a cron to routinely check whether a file or value in DB exists and THEN run (simple polling).

I believe a task queue is a right way to solve this problem. However, I'm not sure how to setup one, and how will the Java process know that a task is waiting for it? Also, would a lot of change be required in my PHP program to put something in task queue?

Thanks a lot!

答:
We faced a similar problem, and used RabbitMQ for message transport, and formatted the messages using Google Protocol Buffers.

RabbitMQ is excellent, it just works.

Protocol buffers format the data compactly (far more so than XML or JSon) and is a known schema allowing interoperability between different languages and machine architectures.

On the Java side, the RabbitMQ Client Library will fire an event when a message is ready to be consumed. Read the RabbitMQ docs and follow through some examples, it'll become clear enough fairly quickly.

On the PHP side, there are RabbitMQ libs you can hook into, you authienticate against a Rabbit host and publish a message. I personally haven't used RabbitMQ with PHP, but given how well it's abstracted for other languages it shouldn't be a huge deal.


问:
Huge long addition overhead compared to Native call?
A run a simple test JDK 1.7.0_45 (Windows 7, 64bit):

Test 1:

```<code>long start = System.nanoTime();
for (int i=0; i < 1000000; i++) {
    System.currentTimeMillis();
}

elapsed = System.nanoTime() - start;
</code>```

Versus Test 2:

```<code>long start = System.nanoTime();
long adjust = 313231;
for (int i=0; i < 1000000; i++) {
    long result = System.currentTimeMillis() + adjust;
}

elapsed = System.nanoTime() - start;
</code>```

On my system, first test ran at around 28 nano/call. The second at around 1250 nano/call. That is a whopping 44x overhead. Can anyone explain such a huge difference?

答: Look at the generated byte code. One obvious explanation would be that your first call to currentTimeMillis() is so obviously useless that the optimizer removed it altogether, and the second isn't. There are countless similar and less similar possible reasons, and speculating about them without looking at what's actually going on is pretty useless.


问:
who should move the sprint status to complete in agile scrum model
we ask the developers themselves to close the sprint once they completed the sprint. Just want to confirm, if it has to be closed by TL after he reviewed the tasks completion. </p>

答:
The Product Owner should be responsible for closing a verified sprint after a successful demo has been done.
The PO should check whether the stories have been "done" to completion in that they meet the correct acceptance criteria.

The developers can "close" the sprint, but the PO needs to verify the completeness of them and "officially" close the sprint and call it done.


问:
Why does java.util.ArrayList allow to add null?
I wonder why java.util.ArrayList allows to add null.  Is there any case where I would want to add null to an ArrayList?

I am asking this question because in a project we had a bug where some code was adding null to the ArrayList and it was hard to spot where the bug was. Obviously a NullPointerException was thrown but not until other code tried to access the element. The problem was how to locate the code that added the null object. It would have been easier if ArrayList threw an exception in the code where the elements was being added.

答:
This seems to be more of a (software-)philosophic question here.

ArrayList as a utility class is designed to be helpful in a wide context of possible use-cases.

Contrary to your hidden claim that accepting null as a valid value should be discouraged, there are many examples where the null value is perfectly legal.

The single most important reason is that null is the do not know equivalent of any reference type, including framework types. This implies that null cannot be replaced in any case by a more fluent version of the nothing value.

So, lets say you store the Integers 1, 3, 7 in your arraylist at its corresponding index:
Due to some computation, you want to get the element at index 5, so what your array
should return is: "no value stored". This could be achieved through returning null
or a NullObject. In most cases returning the built in null value is expressive
enough. After calling a method that can return null and using its return value a check of the returned value against null is quite common in modern code.


答:
Using agile in this situation is still a very good idea.  There are many benefits to agile, only one of which is regular feedback from the customer and the ability to respond to changing requirements as you mention.

One of the main reason waterfall projects are notorious for failure is the 'nearly done' problem - testing produced piles of bugs at the end, leaving an unreleasable product and no idea whether it needs another two days or two years to fix the outstanding bugs.  Agile removes this risk entirely.  If an agile project is over-running, you can still deliver a working version which:

A) Proves to the customer you are actually nearly there through demo's ("All these stories are done, we can do the last few if you want") and some more time will get exactly what they want.

B) Potentially is good enough for them to be happy anyway and release.

To me, removing this risk of complete failure is enough reason alone for a business to move to an agile development process, the ability to build better software than initially planned is icing on the cake.  As mentioned in other answers, those 'concrete' requirements are often still surprisingly malleable.


问:
How to work with large aggregate roots?
I'm learning DDD and yet I have more questions than answers.

Let's consider a model of a directory containing enormous number of files.

Here is how I see it:

Directory is an Aggregate root.

This entity should have the validation logic of checking file name uniqueness when it is added or just renamed. And File entity contains the 'SetName' logic, notifying Directory via Domain Event about name changes.

But how should Directory then work?

It is not always possible to load all files into memory. Should in this case Files repository have adhoc logic for checking name uniqueness? I suppose it is a viable decision.

However, what if some files have been already added or renamed withing current not yet commited transaction? (nothing prohibits that. Transaction boundaries are set externally in relation to business logic). Probably repository should take into account both in-memory and persisted states (merging these states can be nontrivial task.)

So, when aggregate root with all its children fits in memory - everything is fine.
And as soon as you can not materialize all entities there are troubles.

I'd like to know what are the approaches for such situations.
May be there is no problem at all and it is just because of my misunderstanding of the subject.

答:
This this is not a DDD question per se. The main question here is about synchronization context (which is here an aggregate root).

Back on topic:
Directory shall block on some synchronization object of file names and perform a check whether the given file name is allowed which is O(n) in the worst case.

Title: How to work with large aggregate roots?


问:
What exactly is the build number in MAJOR.MINOR.BUILDNUMBER.REVISION
What I think about Build Numbers is that whenever a new nightly build is created, a new BUILDNUMBER is generated and assigned to that build. So for my 7.0 version application the nightly builds will be 7.0.1, 7.0.2 and so on. Is it so? Then what is the use of a REVISION after the build number? Or is the REVISION part being incremented after each nightly build? I am a little confused here... do we refer to each nightly build as a BUILD?

The format is mentioned here: AssemblyVersion - MSDN

答: I've only ever seen a build number as the last number in the release ID.  I'm not sure how you'd come up with a revision to a build number.  I suppose if you changed some of the non-built resources (icons, DB script, etc), maybe, but most projects I've worked on recently have all that stuff under version control as well, so the build process picks them up when making the installer/release.  I like time-stamped build numbers, although not quite as @David describes (I like major.minor.revision.HHMM).  However, where I work, we just use a sequential number that our build server generates.</p>


问:
Is it good practice declare a function inline?
I'm writing a method and depending on a config field I need to change where I get my data from. What this results in me having to write code that looks like this:

```<code>List<string> result = new List<string>();
if (configField)
{
    result.Add(fieldA);
}
else
{
    result.Add(...BusinessLogic...);
}
</code>```

I'll have to write that if statement many many times so of course I want to turn it into a method instead so I can just write result.Add(newMethod(configField, fieldA, dataForBusinessLogicToParse)). This method would be useless to anyone not writing the specific method I'm writing so does it make sense to declare this method as a separate private method or can I just declare it inline as a delegate like this:

```<code>Func<Enum, int, int> newMethod =
    (configField, fieldA, dataForBusinessLogicToParse) => ...businessLogic...
</code>```

I'm worried declaring it inline might make the code more difficult to understand but I think it makes the class cleaner.

答:
As far as I know, declaring a helper method as a lambda like this is not commonly done in C#, so I would advise against doing this unless you have a good reason.

Good reasons include:

The lambda could do something a separate method can't, like closing over a local variable or using anonymous type.

Others in your team agree with you that this is a good practice.

That being said, starting with C# 7.0, C# supports local functions, which are similar to such helper lambdas, but generally better: they have more succinct syntax and are more efficient. So if you used a local function for this purpose, I think that would be perfectly fine.

ContentLicense: CC BY-SA 4.0


问:
Simple straight-line path algorithm
I need a simple pathfinding algorithmn to go from point A to point B.
A* seems like an overkill because It doesn't matter wheather I hit walls or not and there's no terrain. I was wondering if there was a simpler one which would find a direct path(a straight line) from point A to B.</p>

答: Your question might be better placed on gamedev, but if you aren't worried about terrain and/or walls, then what you want is not a path-finding algorithm.  The difference between the two points (or vectors) is the "step" required to get from point A to point B instantly.  You therefore simply need to divide the difference, using some amount, to determine the "step", and apply that each frame.

Title: Simple straight-line path algorithm


问:
When does a Monad become a hammer?
I realize my precursory understanding on Monads is severely lacking in detail considering my knowledge comes mostly from Douglas Crockford's Monads and Gonads talk and complicated with my sevear handicap with Haskell (which looks like a bunch of non-alpha numeric characters mushed between disjointed English words to my tragically disadvantaged brain).

With that being said, I'd like to ask about programming practices concerning Monads and how they could be implemented in JavaScript. I'm prefacing this because I recognize that the very nature of the language can drastically affect how one perceives a concept and that because of my background in JavaScript this question could be inappropriate if it were based in a purely functional language like Haskell.

Often times while designing an interface or coding an object I will find myself implementing a form of chaining which mutates the encapsulated data. I prefer this style over more declarative forms like passing in a multi-lined object literal.

```<code>function Declarative(options) {
  this.options = options;
}
Declarative.prototype.compute = function() { ... }
var x = new Declarative({
  foo: 'foo',
  bar: 'bar'
});
x.compute();
</code>```

Verses:

```<code>function Chained() { }
Chained.prototype.withFoo = function(v) {
  this.foo = v;
  return this;
};
Chained.prototype.withBar = function(v) {
  this.bar = v;
  return this;
};
Chained.prototype.compute = function() { ... }
var x = new Chained()
  .withFoo('foo')
  .withBar('bar')
  .compute();
</code>```

Both these examples (aesthetics aside) raise a few hairs on my back because a small voice mockingly squeals "Mutability much?" I begin thinking this might be a good time to conciser a Monad pattern. What I mean by that is each method would in short return a new object of the same type. Then adding composition functions on it like map, bind, etc. could off a world of potential like I get with Promises and other Monad type. (Obviously taking care to follow the three Monadic laws when implemented).

Finally, my other half of the brain starts chiming in with "If all you have is a hammer, everything looks like a nail." Sigh. That is when my productivity and creativity crash here on SE curious and confused.

While I continue my research for understanding (perhaps gaining enough courage to contemplate Haskell) I ask: When does the idea of Monads (that being composability of functions on objects (ie types) along with immutability) become a good idea to be cultivated and patterned? And, when is it nothing more then an over utilized hammer?

(Concepts and learning opportunities welcomed, example code helpful)

答:
It's hard to tell exactly what you're asking, so this answer is aimed at providing more context about monads.  Some preliminaries about monads:

Crockford's monad talk is a poor source for learning about monads (I hate to say this because he's so much smarter than me, and therefore probably understand monads better than I do, but IMHO it gives an inaccurate portrayal of monads).  So are lots of other monad "tutorials".  If you don't put in hard work making your way through real examples, you'll probably never understand monads.

monads are neither special nor magical.  They can be implemented in many (most? all?) programming languages without special support from the language/runtime/compiler/interpreter.  They aren't the end-all, be-all of functional programming.  But for some reason, they're what we hear about all the time.

monads aren't unique.  There are many other related datatypes which are useful in their own right.

there are alternatives to monads, depending on what you want/need to do.  Search for "effects systems" and "algebraic effects".

you can often get most/much of the value of monads without explicitly using them.  Just implement the combinators that you need and are useful and use them appropriately.  Recognize patterns in your code and factor them out, possibly capturing them as combinators.  If some of those combinators happen to match the requirements for unit and join, so be it.  That doesn't mean you have to think about what you're doing in terms of monads.  (But on the other hand, if you do use monads, you benefit from the numerous combinators already in existence for monads, as well as from writing super-generic code).

When is it inappropriate to use monads?

if you have to warp your datatype or the monad laws in order to "make" a monad, you probably shouldn't do that, and should instead ask yourself why you're doing that

if your code doesn't benefit from using a monad, or if it actually gets worse (whether because it's longer, or harder to understand, or harder to test, or harder to maintain, ... etc.), you're probably using monads inappropriately

Title: When does a Monad become a hammer?


问:
Keep or discard tests that use methods now private
When writing object-oriented code from scratch, I try to follow these steps:

Write a test that fails.

Write a function that makes the test pass.

When enough tests and functions are complete, refactor functions with similar signature into a class.

When the class functionality is complete, make private as many of the class methods as possible.

The last step seems sound to me, since object orientation is all about hiding complexity behind abstractions, and keeping the public part of those abstractions as small as possible.

However, this leads me to discard many of the tests that I wrote when still working with plain functions — since they are now testing the private part of a class' API. This makes me uncomfortable because:

remaining tests are suddenly forced to "cover more complexity".

For instance: if I wrote a method to swap_rows in a matrix while inverting it, but that method is now private and only used from the public method invert, then the test_invert has to somehow convey to the reader that "swapping rows happens while inverting".

More importantly, that remaining test possibly will not pinpoint that it is the swapping of rows that has been broken by a careless change (and not any other part of the inverting process).

private class methods may become public again when writing client code that has a reasonable cause to access their results.

This is difficult to foresee.  Recovering the tests from a previous commit is possible but it feels like wasted time.

A solution would be to refactor the methods out into a helper class that is package private.  However, this looks like abusing object-oriented principles for the sake of TDD principles; also, it makes me wonder if there will ever be a good reason to make something private at all.

I realize I am asking here about "how to grow an architectural design", and that this cannot be done in a completely "bottom-up" approach; but I would like practical advice on keeping or discarding such early tests while still figuring out the shape of a piece of software.

This question is similar, but here I do not question that it is possible to get an initial public API right with TDD:  I seek for good advice on how to get there. This answer is useful, but I do not think I am trying to adapt my coding to my tests, but rather my tests to my — still uncertain — design.

To summarize: should I keep or discard early tests while writing object-oriented code from scratch?  Should I still strive to make as many methods as possible private, or is this leading me to a bad design and the forced removal of tests is just a symptom thereof?

答:
IMMO the problem its that you are thinking in testing functions and classes instead of thinking in testing the exposed behavior of your system.

When your are testing exposed behaviors you only change your test when you change the behavior your system exposes; this includes removing tests when some behavior is not exposed anymore.

As a drawback to this, sometimes testing only exposed behavior is difficult because this behavior implementation is complex, and probably you want to do some internal testing too. This of course depends entirely in the complexity on the system but I recommend only make separated test for those things you think are more stable, for example some internal complex algorithms or things like that.


答:
Dijkstra's Algorithm

You could apply the algorithm that A* is based on: Dijkstra's algorithm with the assumption that travel to each neighboring node is equal. This will still give you the shortest path (or paths as your network may vary) However you might still view this as overkill (since you make no mention of shortest path, only of linear)

Implement Basic Pathfinding Yourself

I suggest you check out the Artificial Intelligence Depot Beginner tutorial for path finding. It contains pseudocode for a very simplistic path finding algorithm and explains the basics in the logic required for understanding and implementing them. I have included the pseudocode below for your benefit:

```<code> create a list P
 add the start node S, to P giving it one element
 Until first path of P ends with G, or P is empty
    extract the first path from P
    extend the path one step to all neighbors creating X new paths
    reject all paths with loops
    add each remaining new path to P
 If G found -> success. Else -> failure.
</code>```

Please note that

"This also assumes there is a tree or network from which contains the
paths to be followed."

A - But simpler*

Other than that you can still use the A* algorithm and just make a very simple evaluator to determine heuristics for the best next step. In that case it would be very simple to use Euclidean distance (think absolute distance) to get your path. If you are interested, I've found that I learned a lot from Patrick Lester's tutorial for beginners and from Coke and Code's article on A*.

I hope this helps you implement what you are looking for.

Title: Simple straight-line path algorithm

Body:
I need a simple pathfinding algorithmn to go from point A to point B.
A* seems like an overkill because It doesn't matter wheather I hit walls or not and there's no terrain. I was wondering if there was a simpler one which would find a direct path(a straight line) from point A to B.</p>

Body:
Dijkstra's Algorithm

You could apply the algorithm that A* is based on: Dijkstra's algorithm with the assumption that travel to each neighboring node is equal. This will still give you the shortest path (or paths as your network may vary) However you might still view this as overkill (since you make no mention of shortest path, only of linear)

Implement Basic Pathfinding Yourself

I suggest you check out the Artificial Intelligence Depot Beginner tutorial for path finding. It contains pseudocode for a very simplistic path finding algorithm and explains the basics in the logic required for understanding and implementing them. I have included the pseudocode below for your benefit:

 create a list P
 add the start node S, to P giving it one element
 Until first path of P ends with G, or P is empty
    extract the first path from P
    extend the path one step to all neighbors creating X new paths
    reject all paths with loops
    add each remaining new path to P
 If G found -> success. Else -> failure.

Please note that

"This also assumes there is a tree or network from which contains the
paths to be followed."

A - But simpler*

Other than that you can still use the A* algorithm and just make a very simple evaluator to determine heuristics for the best next step. In that case it would be very simple to use Euclidean distance (think absolute distance) to get your path. If you are interested, I've found that I learned a lot from Patrick Lester's tutorial for beginners and from Coke and Code's article on A*.

I hope this helps you implement what you are looking for.


问:
Are the over-usage of delegates a bad thing?
Good day.

I have been told that a good practice for writing methods is to make the method only responsible for doing one thing. It made sense to me now that I look back upon it in retrospect. There are a couple of reasons I like coding in such a way - to me they are:

Code is Manageable

Code is more human readable

Better understanding of what the method does is maintained

But here comes the issue which concerns me. Sometimes performing a task requires more than 1 action to be performed. A lot of developers' code which I look at every day does 7 to 8 things per method, where it could have been broken up and assigned to a delegate to run the methods sequentially.

Working on huge projects, what will the implications be of using a lot of delegates to run methods sequentially? Should I be concerned for using a lot of delegates in my code?

Example-

```<code>private delegate void Factory();
    Factory factory = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            factory += SetCatalogClientProxy;
            factory += SetHelper;
            factory += GetAccessToken;
            //factory += GetCatalog;
            factory += GetToken;
            factory.Invoke();
        }
        catch (Exception ex)
        {
            AddToResult(ex.Message + NEWLINE + ex.StackTrace.Replace(" at ", " at " + NEWLINE).Replace(" in ", " in " + NEWLINE));
        }
    }

    #region Test Process Methods

    private void SetCatalogClientProxy()
    {
        catalog = new JAM.CatalogClientProxy();
        AddToResult("CatalogClientProxy Successfully initialized");
    }

    private void SetHelper()
    {
        helper = new JAM.HelperClass();
        AddToResult("HelperClass Successfully Intialized");
    }

    private void GetAccessToken()
    {
        accessToken = JAM.CatalogClientProxy._accessToken;
        if (string.IsNullOrEmpty(accessToken))
        {
            catalog.GetACSClaim();
            accessToken = JAM.CatalogClientProxy._accessToken;
        }
        AddToResult("Accesstoken Retrieved." + NEWLINE + accessToken);
    }

    private void GetCatalog()
    {
        catalog.CallCatalogService("fullcatalog", utcTime, country, "2", false);
        AddToResult(helper.Catalog(baseUrl, utcTime, page, country, accessToken));
    }

    private void GetToken()
    {
        var Fulfillment = new JAM.FulfillmentServiceProxy(Guid.NewGuid().ToString());
        ClassImport.FulfillmentInfo result = Fulfillment.GetToken("ABC-11111", "123456", "ZA", "123456", "123456", JAM.CatalogClientProxy._accessToken);

        if (result != null)
        {
            var output = "Products" + NEWLINE;
            foreach (var p in result.Products)
            {
                output += "    " + p.ProductName + "<br/>";
                foreach (var l in p.Links)
                {
                    output += "        " + l.Uri + "<br/>";
                }
            }
            AddToResult(output);
        }
        else
        {
            AddToResult("No products Found");
        }
    }
    #endregion

    #region Logging To Page

    private void AddToResult(string text)
    {
        result.InnerHtml += String.Concat("<strong>[", DateTime.Now.ToString(), "]</strong> ", text, NEWLINE);
    }

    #endregion
</code>```

This is from one of my test pages. There is only 1 delegate here, but on other projects I work on I sometimes have 5 or 6 delegates set up similarly to perform methods sequentially, where I try to keep the methods at 1 action each.

答:
I have been told that a good practice for writing methods is to make the method only responsible for doing one thing.

The common problem people have with this is that they take it too literally. If a function can only ever do one thing, how do you ever do more than one thing ever?

If your "one thing" takes 5 steps, then make a single function that does these 5 steps, and only those 5 steps. In turn, each of those steps should be a function that does that step, and only that step (which in turn may be 3 smaller steps).

A single responsibility necessarily requires multiple smaller responsibilities or else you wouldn't be writing a method... you'd just use the smaller responsibility directly.

Working on huge projects, what will the implications be of using a lot of delegates to run methods sequentially?

Delegates tend to be a weaker contract than other associations. Since it can do anything as long as it meets the delegate signature, your code can become very fragile and hard to reason about.

I'd say... half of C# developers or so don't even know that delegates are multicast.

The exception handling behavior in multicast delegates isn't going to be what you always want.

The optimizer (and JITer) can do far, far less with delegates compared to a real function. The impact will vary depending on your compiler and target runtime. Measure to be sure.


问:
What design pattern should I use for import, update, export
I need to create a simple payments validator. On the following class diagram, I tried to present the model of payments. As you can see, each payment type inherits from Payments class.

Now I want to work with these payments but hide the details so the user can only access what he needs. And those things are are:

Load payments from path and return list of payments

Save payments to path

Update input payments list and return updated list

I am not sure if the way I am doing it is correct.

My idea would be to use Facade design pattern, so PaymentsModel class which would contain following methods should be created:

```<code>public class PaymentsModel
{

    IList<ToBePaidPaymentsDto>  GetToBePaidPayments(string path){
         return new IList<ToBePaidPaymentsDto>();
    }

    IList<DonePaymentsDto>  GetDonePayments(string path){
         return new IList<DonePaymentsDto>();
    }

    IList<MissedPaymentsDto>  GetMissedPayments(string path){
         return new IList<MissedPaymentsDto>();
    }

    ...

}
</code>```

Then create abstract class:

```<code>public abstract class Payments<T>
{
    protected string Delimiter {get; private set;}
    protected int NumberOfHeaders {get; private set;}

    public abstract IList<T> LoadRecords(string path);

    public abstract IList<T> UpdateRecords(IList<T> records);

    public void SaveRecords(string path, DataGridViewRowCollection records)
    {
    }
</code>```

}

where T is Data Transfer Object depending on the type of payments, so:

ToBePaidPayments class would use ToBePaidPaymentsDto

DonePayments class would use DonePaymentsDto

as presented below

```<code>public class PaymentsToBePaid : Payments<IcsToBePaidPaymentDto> {

    public override IList<IcsToBePaidPaymentDto> LoadRecords(string path){

        return null;
    }

    public override  IList<IcsToBePaidPaymentDto> UpdateRecords(IList<IcsToBePaidPaymentDto> records){

        return null;
    }

}
</code>```

and

```<code>public class PaymentsDone : Payments<IcsDonePaymentDto>
{
    public override IList<IcsDonePaymentDto> LoadRecords(string path){

        return null;
    }

    public override IList<IcsDonePaymentDto> UpdateRecords(IList<IcsDonePaymentDto> records){

        return null;
    }

}
</code>```

Now, my final question is - am I doing this correctly? Am I applying correct design pattern and am I applying it correctly?
Thank you for advice.

答:
Given your comment that payments have different fields based on their status (and I will therefore assume this is an issue because of database tables), then What I'd do is implement a CsvReader class that has a generic-type argument, that maps Csv fields to the POCO in question.  Therefore you'd write a single Csv Importer, and that can then be used to import data regardless of what class you throw at it.

Similarly, you can write a CsvExporter class that does the same thing.  Write once, use everywhere.

Some comments:

Remove the Dto extension.  We know what a payment is, it can potentially be used in many places (the database, the Csv File, business logic).  Dto is relevant in a single, specific scenario.

Consider changing Todo to Pending.


答:
If you are trying to find a path through an array of terrain squares, or else a path through a connected set of nodes, then breadth-first or depth-first traversal work well. (One trick to limit the size of the traversal to do a breadth-first search, but start a traversal at both the start point and the end point, and stop at the first cell that both have reached.)

However, if you're just drawing a line from A to B on some grid, then basic line-drawing algorithms work. A classic one is Bresenham's line algorithm, which is pretty simple.

If you want a simpler version that just distributes steps on the X axis with steps on the Y axis, it looks like this. It's kind of like "division by adding". This is just the basics -- lots and lots of room for improvements! (python)

```<code>def line(x0, y0, x1, y1):

    # number of steps x and y
    mx = abs(x1 - x0)
    my = abs(y1 - y0)

    # the greater number of steps
    steps = max(mx, my)
    sx = 0
    sy = 0

    x = x0
    y = y0
    path = [(x0, y0)]

    while x != x1 or y != y1:
        sx += mx
        sy += my

        if sx >= steps:
            sx -= steps
            x += 1  # only one direction for now

        if sy >= steps:
            sy -= steps
            y += 1  # only one direction for now

        #print((sx, sy, mx, my))

        path.append((x,y))

    return path

if __name__ == '__main__':
    print(line(0, 0, 8, 8))
    print(line(0, 0, 4, 8))
    print(line(0, 0, 8, 4))
    print(line(0, 0, 0, 8))
    print(line(0, 0, 8, 0))
</code>```

I used to tweak this algoritmn to create circular or elliptical arcs, oblique lines (i.e. one that come at the target at a slight angle), perpendicular paths, or even just running straight away from the target! I probably spent more time on this than I should have as a youth. ;)

...

One more thought; if you're programming a "chase" algorithm, where a robot chases some target, then there are a few fun variations on that. You don't have to calculate the full path.

Move diagonally or along an axis: x += 1 if x1 > x0, x -= 1 if x1 < x0

Move along 45 degree lines: x += 1 if dx > dy / 2 etc.

Another fun one is to move the robot x += dx / 10 ... while it's not taking constant steps, it makes for a pretty cool display if you have a bunch of randomly scattered bots chasing each other.

...

One more thought. This works when x and y are spacial dimensions (like in a grid or array), but also works if one of the dimensions is time. So, for example, if you want to distrubute 5 messages across 8 seconds, then you can treat y as time, and use the same loop to distribute some number of events across some time span.

Title: Simple straight-line path algorithm

Body:
If you are trying to find a path through an array of terrain squares, or else a path through a connected set of nodes, then breadth-first or depth-first traversal work well. (One trick to limit the size of the traversal to do a breadth-first search, but start a traversal at both the start point and the end point, and stop at the first cell that both have reached.)

However, if you're just drawing a line from A to B on some grid, then basic line-drawing algorithms work. A classic one is Bresenham's line algorithm, which is pretty simple.

If you want a simpler version that just distributes steps on the X axis with steps on the Y axis, it looks like this. It's kind of like "division by adding". This is just the basics -- lots and lots of room for improvements! (python)

def line(x0, y0, x1, y1):

    # number of steps x and y
    mx = abs(x1 - x0)
    my = abs(y1 - y0)

    # the greater number of steps
    steps = max(mx, my)
    sx = 0
    sy = 0

    x = x0
    y = y0
    path = [(x0, y0)]

    while x != x1 or y != y1:
        sx += mx
        sy += my

        if sx >= steps:
            sx -= steps
            x += 1  # only one direction for now

        if sy >= steps:
            sy -= steps
            y += 1  # only one direction for now

        #print((sx, sy, mx, my))

        path.append((x,y))

    return path

if __name__ == '__main__':
    print(line(0, 0, 8, 8))
    print(line(0, 0, 4, 8))
    print(line(0, 0, 8, 4))
    print(line(0, 0, 0, 8))
    print(line(0, 0, 8, 0))

I used to tweak this algoritmn to create circular or elliptical arcs, oblique lines (i.e. one that come at the target at a slight angle), perpendicular paths, or even just running straight away from the target! I probably spent more time on this than I should have as a youth. ;)

...

One more thought; if you're programming a "chase" algorithm, where a robot chases some target, then there are a few fun variations on that. You don't have to calculate the full path.

Move diagonally or along an axis: x += 1 if x1 > x0, x -= 1 if x1 < x0

Move along 45 degree lines: x += 1 if dx > dy / 2 etc.

Another fun one is to move the robot x += dx / 10 ... while it's not taking constant steps, it makes for a pretty cool display if you have a bunch of randomly scattered bots chasing each other.

...

One more thought. This works when x and y are spacial dimensions (like in a grid or array), but also works if one of the dimensions is time. So, for example, if you want to distrubute 5 messages across 8 seconds, then you can treat y as time, and use the same loop to distribute some number of events across some time span.


问:
optimize human-readable database with index
i need to store a large amount of data - about 10 million entries of the format

```<code>unique hash (64 chars), value 1 (5 chars), value 2 (9 chars)
</code>```

i will be reading and deleting (but not updating) this data in quick succession. for example, i might write 10 lines, then read 3 and delete 3 lines, before moving on to more writes and reads...

its a single threaded desktop program so reads are only initiated after writes and deletes have been completed. i would like to avoid using a database so that the data can be human-readable from the file system and so that people who download and use my program can see it and inspect it for themselves. i expect my users to be running a linux os and my program is written in python.

i have come up with three possible options for how to store this data:

option 1

put the data in a single file. since the hashes are unique i can arrange them in ascending order like an index so as to give log2 N read times. deleting and inserting will happen often and would slow the process down as N gets large.

option 2

use the unique hash as a file name and put the values inside this file. this would be my preferred option so long as there are no obvious performance drawbacks? i know some file systems slow down when a large number of files exist in a single directory. and i really can't make any assumptions about which file system the users of my program will be using. i need to choose a solution which is quick on all file systems.

option 3

use the unique hash to create a directory to store the values in. so for example, if a record has hash abcd then i would create dir and file base_dir/a/b/c/d.txt. does this get around the file system performance issue issue? or is this just as bad as option 2 depending on the type of file system the user is running?

question

so really i'm just looking for help to decide which option to pick. also if you have any other options that are superior to the ones i have listed here i would like to hear them. maybe some database software like mysqli that sores data in human-readable text? that would be ideal really, but i imagine that most databases would use binary for efficiency...

答:
There is a reasonably obvious solution: a directly hashed file store.

To deal with your suggestions:

Slowish access, horribly slow delete and insert. Forget it.

No file system can give you a million files in reasonable time. Forget it.

Doable but complicated to work out a decent scheme. Not my choice.

For a directly hashed file store you divide the file into buckets (say 4000 bytes, holding 80 keys). You devise a hash function of your unique hash that distributes keys evenly across buckets. You place each record in that bucket. You allocate some number of overflow buckets for keys when the bucket they belong in is full.

You can find any record in just over O(1) by a single calculation and a single (bucket) read, followed by searching the bucket for the right record. You can add or delete a record by one extra write. You aim for about 80-90% full, depending on how good your has function is at distributing keys into buckets. if it's too full you will have to go to an overflow bucket too often and that costs performance.

You can easily find details of how to implement this kind of scheme. It's a very old technique from pre-database days. Very fast, reasonably simple and a perfect match for your problem.


答:
Most of what I would say in response to your question has been said by others. Read "Things You Should Never Do, Part I" by Joel Spolsky (along with some of his other posts about "architecture astronauts"). Remember that "the perfect is the enemy of the good". Learn to refactor incrementally. Shipping is important, etc.

What I would add is this: you've been tasked with something that was considered doable by a single fresh graduate working with a small startup budget / timeframe. You shouldn't need anything much more sophisticated than good, structured, procedural programming. (And, FYI, "procedural programming" is not a bad word. It's a necessity at some level in most cases, and it's wholly adequate for many entire projects.)

Just make sure you actually do structured, procedural programming. Repetition in your code is not necessarily a sign that you need grand, polymorphic structures. It could simply be a sign that you need to take the repeated code and put it into a subroutine. "Spaghetti" control flow may simply be an opportunity to get rid of a global.

If there are aspects of the project that legitimately call for polymorphism, implementation inheritance, etc., I would suggest that maybe the size of the project was underestimated.

Title: Project is nearly done, but procedural spaghetti code. Do I rewrite or just keep trying to ship it?

Body:
I'm a beginner web developer (one year of experience).

A couple of weeks after graduating, I got offered a job to build a web application for a company whose owner is not much of a tech guy. He recruited me to avoid theft of his idea, the high cost of development charged by a service company, and to have someone young he can trust onboard to maintain the project for the long run (I came to these conclusions by myself long after being hired).

Cocky as I was back then, with a diploma in computer science, I accepted the offer thinking I can build anything.

I was calling the shots. After some research I settled on PHP, and started with plain PHP, no objects, just ugly procedural code. Two months later, everything was getting messy, and it was hard to make any progress. The web application is huge. So I decided to check out an MVC framework that would make my life easier. That's where I stumbled upon the cool kid in the PHP community: Laravel. I loved it, it was easy to learn, and I started coding right away. My code looked cleaner, more organized. It looked very good.

But again the web application was huge. The company was pressuring me to deliver the first version, which they wanted to deploy, obviously, and start seeking customers.

Because Laravel was fun to work with, it made me remember why I chose this industry in the first place - something I forgot while stuck in the shitty education system.

So I started working on small projects at night, reading about methodologies and best practice. I revisited OOP, moved on to object-oriented design and analysis, and read Uncle Bob's book Clean Code.

This helped me realize that I really knew nothing. I did not know how to build software THE RIGHT WAY. But at this point it was too late, and now I'm almost done. My code is not clean at all, just spaghetti code, a real pain to fix a bug, all the logic is in the controllers, and there is little object oriented design.

I'm having this persistent thought that I have to rewrite the whole project. However, I can't do it... They keep asking when is it going to be all done.

I can not imagine this code deployed on a server. Plus I still know nothing about code efficiency and the web application's performance.

On one hand, the company is waiting for the product and can not wait anymore. On the other hand I can't see myself going any further with the actual code. I could finish up, wrap it up and deploy, but god only knows what might happen when people start using it.

Do I rewrite, or just keep trying to ship, or is there another option that I've missed?


问:
should Product owner be in product management team
Should the product owner ideally be as part of the product management team?
How does one handle the internal stakeholding if the product owner is outside the product management team?

We had problems since the product owner was not part of the product management team and there were lot of conflicts.

答:
Agile is more of a brand then a methodology, which type do you mean in particular?

In scrum for example, yes, it would be common to map a previous project manager to a product owner. Although much of the responsibility of the project managing would fall to the scrum master and the team, the skill set required to be a PO (communicating the customers needs, managing customer expectations, directing team efforts towards business value and being the guy who's accountable) are close to those of a PM. However, it is also possible to have a more technical PO or one that more directly represents the customer.

Here's the thing though. The fact you have product management team to conflict suggests that that  text above isn't really relevant, because you may be doing cargo cult agile, with the PM and  the PO replicating each others work. Do you still have a traditional project manager for example?


答:
Ideally you want the product owner to be the person who signs off on the final product. They should be either the client you're selling the product to, or, if that's not possible, the final person who is selling the product to the customer. The idea is that this person knows what the final product should be and can guide it's development from afar by ranking user stories and providing feedback at the end of sprints.

Of course, sometimes you can't/don't want to give the customer the ability to see what you're making as you're making it, so you'll have to find a product owner that fits your team's needs. I've worked in both situations and honestly, having someone who knows how to rank features and be a good product owner is often more helpful than having the customer do it, as the customer tends to make everything super high priority, and doesn't understand how software development works well enough to know time estimation.

Title: should Product owner be in product management team

Body:
Should the product owner ideally be as part of the product management team?
How does one handle the internal stakeholding if the product owner is outside the product management team?

We had problems since the product owner was not part of the product management team and there were lot of conflicts.


问:
Why can you have statefulness inside a static class in java?
I was playing around with Java today and I read about static inner classes. Why can you have 'statefulness' inside of a static inner class. For instance:

```<code>class outerClass {
        static class Test {
        private String a;

        String getA() { return a; }

        void setA( String newA) {a = newA; }

    }
}
</code>```

Am I misunderstanding something? It seems like you should not be able to keep mutable state inside of a class that is labled at static. Moreover it seems like you should not be able to instantiate something that is a static class, it should be a static singleton. Perhaps someone could correct me if I am making an incorrect assumption or enlighten me to why the Java authors decided to make this possible.

EDIT: I feel as if I am confusing the keyword final and static in java, as final variables do not have state. It still seems very strange to be able to instantiate a static class, though.

答: You can keep static state.  It is just associated with the class, rather than with the object instance.  So every object instance sees the same state value.</p>


答:
A static inner class is the same as a non-inner class. Your example is equivalent to:

```<code>class outerClass {}

class Test {
    ...
}
</code>```

The static in static inner classes means that instances of the inner class aren't associated with an instance of the outer class. Without static, an instance of Test is always attached to an instance of outerClass - you'd need to construct an instance of outerClass before you can construct an instance of Test and the instance of Test would have access to the members of outerClass.

Title: Why can you have statefulness inside a static class in java?

Body:
I was playing around with Java today and I read about static inner classes. Why can you have 'statefulness' inside of a static inner class. For instance:

```<code>class outerClass {
        static class Test {
        private String a;

        String getA() { return a; }

        void setA( String newA) {a = newA; }

    }
}
</code>```

Am I misunderstanding something? It seems like you should not be able to keep mutable state inside of a class that is labled at static. Moreover it seems like you should not be able to instantiate something that is a static class, it should be a static singleton. Perhaps someone could correct me if I am making an incorrect assumption or enlighten me to why the Java authors decided to make this possible.

EDIT: I feel as if I am confusing the keyword final and static in java, as final variables do not have state. It still seems very strange to be able to instantiate a static class, though.

Body:
A static inner class is the same as a non-inner class. Your example is equivalent to:

class outerClass {}

class Test {
    ...
}

The static in static inner classes means that instances of the inner class aren't associated with an instance of the outer class. Without static, an instance of Test is always attached to an instance of outerClass - you'd need to construct an instance of outerClass before you can construct an instance of Test and the instance of Test would have access to the members of outerClass.


答:
static things aren't always stateless.  Instead, static refers to the ability to access the instance variables and methods in an object.

With nested classes in Java, the static modifier on the inner class refers to its access to the outer class.

A static inner class does not have access to the instance variables of its enclosing class (just like a static method doesn't have access to the instance variables).  A further implication of this is that because the static inner class doesn't have the ability to access the instance variables it can be instantiated separately from the outer class. However, there is nothing in this definition that implies the lack of state.

The reason to use a static inner class is to further encapsulate it so that it can't tinker with its outer class member variables or methods.

With a later edit and some confusion about static, final and state:

I feel as if I am confusing the keyword final and static in java, as final variables do not have state. It still seems very strange to be able to instantiate a static class, though.

I must point out that final variables have state too. It is just a state that can be assigned once and only once.  Consider:

```<code>final int foo;
if(bar) {
    foo = 42;
} else {
    foo = 4;
}
</code>```

Perfectly valid and stateful code on a final variable.

A static inner class that you can't instantiate is a situation that I can't quite find a use case for. Yes, the Java designers used static in yet another way (import, class, block, field, method, and inner class too). Each different use of static is distinct and should be considered to be separate concepts that sometimes interact.

In this case, the static inner class is more akin to a static method than a static class.

Body:
static things aren't always stateless.  Instead, static refers to the ability to access the instance variables and methods in an object.

With nested classes in Java, the static modifier on the inner class refers to its access to the outer class.

A static inner class does not have access to the instance variables of its enclosing class (just like a static method doesn't have access to the instance variables).  A further implication of this is that because the static inner class doesn't have the ability to access the instance variables it can be instantiated separately from the outer class. However, there is nothing in this definition that implies the lack of state.

The reason to use a static inner class is to further encapsulate it so that it can't tinker with its outer class member variables or methods.

With a later edit and some confusion about static, final and state:

I feel as if I am confusing the keyword final and static in java, as final variables do not have state. It still seems very strange to be able to instantiate a static class, though.

I must point out that final variables have state too. It is just a state that can be assigned once and only once.  Consider:

final int foo;
if(bar) {
    foo = 42;
} else {
    foo = 4;
}

Perfectly valid and stateful code on a final variable.

A static inner class that you can't instantiate is a situation that I can't quite find a use case for. Yes, the Java designers used static in yet another way (import, class, block, field, method, and inner class too). Each different use of static is distinct and should be considered to be separate concepts that sometimes interact.

In this case, the static inner class is more akin to a static method than a static class.


问:
HTML - Alternative for ID when ID is only unique within a certain scope?
So I feel like this should be a common question but I can't find the answer. Maybe I'm using the wrong terminology.

Assumptions:

IDs are supposed to be unique across the document.

Class attributes are meant for CSS and should not be used in JS selectors.

Name attributes are not appropriate ID replacements since they don't work the same on all elements and the html 5 spec changed them (removed from certain elements I think).

So given something like:

The page has multiple of the same widget. Each widget has a unique ID. I need to be able to reference widget sub-elements like $("#widgetID relativeID"). So that relative IDs are unique within widgets but may be duplicated outside this scope.

I had been using name for this but it seems this isn't the correct way

What is?

答: Combine the two ID's together, as in ID="WidgetID_RelativeID"  This will guarantee uniqueness.


答:
You first and third assumptions are solid. You middle assumption "class attributes are meant for CSS and should not be used in JS selectors" is completely, utterly wrong. Granted, there's some structural / separation-of-concerns purity about it. But it rejects the reality and common practice of almost all dynamic JavaScript modification of HTML documents.

If you only have one of a thing on a page, and you know that's not going to change, the id attribute works well for both CSS and JS. When there are possibly more than one of a thing, the class attribute is precisely the place to note this. jQuery and all other modern "higher level JavaScript" libraries bake this kind of usage right into their code, documentation, and examples, and everyone uses class selectors in this way.

Relative ids are not a standard part of either CSS or JS parlance, and they probably never will be. The very idea suggests taking something that is absolute and making it relative. Given the availability, success, and ubiquity of class selectors, what would be the point? If you want to simulate that kind of access, define unique class selectors and then use the relative (e.g. child, descendant, or adjacent sibling) notation that's already part-and-parcel of CSS and JS usage.

Title: HTML - Alternative for ID when ID is only unique within a certain scope?

Body:
So I feel like this should be a common question but I can't find the answer. Maybe I'm using the wrong terminology.

Assumptions:

IDs are supposed to be unique across the document.

Class attributes are meant for CSS and should not be used in JS selectors.

Name attributes are not appropriate ID replacements since they don't work the same on all elements and the html 5 spec changed them (removed from certain elements I think).

So given something like:

The page has multiple of the same widget. Each widget has a unique ID. I need to be able to reference widget sub-elements like $("#widgetID relativeID"). So that relative IDs are unique within widgets but may be duplicated outside this scope.

I had been using name for this but it seems this isn't the correct way

What is?


答:
Note: This question may be better suited to Stack Overflow rather than programmers.

I would use the .dataset(MDN) to store local IDs. I would access them using element.querySelector(MDN).

Example[1]:

```<code><widget id="AwesomeWidget">
  <div data-ID="Sidebar"></div>
  <div data-ID="Toolbar"></div>
</widget>
</code>```

and I would access them in Javascript using the following approach:

```<code>AwesomeWidget.querySelector("div[data-ID='Sidebar']");
</code>```

[1]: Not valid HTML: Custom-elements must have have a - in their names, so
x-widget is OK but widget is not.

Body:
Note: This question may be better suited to Stack Overflow rather than programmers.

I would use the .dataset(MDN) to store local IDs. I would access them using element.querySelector(MDN).

Example[1]:

<widget id="AwesomeWidget">
  <div data-ID="Sidebar"></div>
  <div data-ID="Toolbar"></div>
</widget>

and I would access them in Javascript using the following approach:

AwesomeWidget.querySelector("div[data-ID='Sidebar']");

[1]: Not valid HTML: Custom-elements must have have a - in their names, so
x-widget is OK but widget is not.


答:
You are right that Class attributes [were originally] meant for CSS, but that doesn't necessarily mean that you cannot also use them as JavaScript hooks.  (But some care is required.)

According to the HTML4 spec,

```<code>The class attribute has several roles in HTML:
    * As a style sheet selector (when an author wishes to assign style information to a set of elements).
    * For general purpose processing by user agents.
</code>```

This doesn't explicitly say whether classes should be used as JS hooks or not (is that "general purpose processing"?).

In the HTML5 spec, all of this language regarding the role of classes is not there.  It simply states that class is, "a set of space-separated tokens representing the various classes that the element belongs to".  Then it reports that class can be used as a JS selector using getElementsByClassName()

That said... I do understand your hesitancy to use the class attribute for the dual purpose of controlling style and behavior.  It is not a good thing to try to change how your page looks, only to realize that you also changed its functionality.

To get around this problem, I have seen a couple of different solutions.

(1)  Name your JavaScript hook classes with a js- prefix.  If you do this, it is clear which classes are meant as JS hooks, and which are not.

```<code><input type="text" class="required js-typeahead" name="some-text" />
</code>```

(2) Use data-* attributes instead of class for JS hooks.  This also gives you the added benefit that you get a key-value pair for your JS code.

```<code><input type="text" class="required" data-typeahead="typeahead" name="some-text" />
</code>```

Of course, you can use data-* attributes for styling, so you don't necessarily get around your separation of style and behavior.

```<code>#input[data-typeahead] {
    background-image:  url("typeahead.png");
    background-repeat: no-repeat;
}
</code>```

Body:
You are right that Class attributes [were originally] meant for CSS, but that doesn't necessarily mean that you cannot also use them as JavaScript hooks.  (But some care is required.)

According to the HTML4 spec,

The class attribute has several roles in HTML:
    * As a style sheet selector (when an author wishes to assign style information to a set of elements).
    * For general purpose processing by user agents.

This doesn't explicitly say whether classes should be used as JS hooks or not (is that "general purpose processing"?).

In the HTML5 spec, all of this language regarding the role of classes is not there.  It simply states that class is, "a set of space-separated tokens representing the various classes that the element belongs to".  Then it reports that class can be used as a JS selector using getElementsByClassName()

That said... I do understand your hesitancy to use the class attribute for the dual purpose of controlling style and behavior.  It is not a good thing to try to change how your page looks, only to realize that you also changed its functionality.

To get around this problem, I have seen a couple of different solutions.

(1)  Name your JavaScript hook classes with a js- prefix.  If you do this, it is clear which classes are meant as JS hooks, and which are not.

<input type="text" class="required js-typeahead" name="some-text" />

(2) Use data-* attributes instead of class for JS hooks.  This also gives you the added benefit that you get a key-value pair for your JS code.

<input type="text" class="required" data-typeahead="typeahead" name="some-text" />

Of course, you can use data-* attributes for styling, so you don't necessarily get around your separation of style and behavior.

#input[data-typeahead] {
    background-image:  url("typeahead.png");
    background-repeat: no-repeat;
}


问:
In wikipedia it is referred that Remote Socket Address is the Client Socket Address but i doubt that
In the context of Network Socket , which one is the REMOTE SOCKET ADDRESS?? Does the Client Socket Address refer to the Remote Socket Address?</p>

答:
In the context of Network Socket , which one is the REMOTE SOCKET ADDRESS??

Both sockets are remote, one from the other. If, in some specific context, you label one socket "local", the other must be remote. You give no such context.

Does the Client Socket Address refer to the Remote Socket Address?

In the context of the client process, its socket is local and the server's is remote.

In the context of the server process, its socket is local and the client's is remote.

You might as well ask, "which end of the pipe is called the far end?"  The answer depends on which end you're holding at the time.


问:
What do you use string reversal for?
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.

答:
For compilers ?

It's amusing, but most symbols in a language will begin by a common pattern. I am not talking about Hungarian Notation here, but if you think about namespace / classes, then a lot of symbols will actually share a common prefix.

```<code>myproject::SomeClass::GetFoo
myproject::SomeClass::GetBar
</code>```

The problem is, when doing a binary search, common prefixes are the worst thing you can end up with, because you'll end up comparing those prefixes over and over again.

On the other hand, if you get a look at the strings backward, you'll see much more entropy! And then suddenly a binary search (over a Trie) gets much more powerful!

It's always bugged me that C++ mangled names (by gcc) were not reversed to put the namespace LAST :)

Title: What do you use string reversal for?

Body:
For compilers ?

It's amusing, but most symbols in a language will begin by a common pattern. I am not talking about Hungarian Notation here, but if you think about namespace / classes, then a lot of symbols will actually share a common prefix.

myproject::SomeClass::GetFoo
myproject::SomeClass::GetBar

The problem is, when doing a binary search, common prefixes are the worst thing you can end up with, because you'll end up comparing those prefixes over and over again.

On the other hand, if you get a look at the strings backward, you'll see much more entropy! And then suddenly a binary search (over a Trie) gets much more powerful!

It's always bugged me that C++ mangled names (by gcc) were not reversed to put the namespace LAST :)


问:
Project is nearly done, but procedural spaghetti code. Do I rewrite or just keep trying to ship it?
I'm a beginner web developer (one year of experience).

A couple of weeks after graduating, I got offered a job to build a web application for a company whose owner is not much of a tech guy. He recruited me to avoid theft of his idea, the high cost of development charged by a service company, and to have someone young he can trust onboard to maintain the project for the long run (I came to these conclusions by myself long after being hired).

Cocky as I was back then, with a diploma in computer science, I accepted the offer thinking I can build anything.

I was calling the shots. After some research I settled on PHP, and started with plain PHP, no objects, just ugly procedural code. Two months later, everything was getting messy, and it was hard to make any progress. The web application is huge. So I decided to check out an MVC framework that would make my life easier. That's where I stumbled upon the cool kid in the PHP community: Laravel. I loved it, it was easy to learn, and I started coding right away. My code looked cleaner, more organized. It looked very good.

But again the web application was huge. The company was pressuring me to deliver the first version, which they wanted to deploy, obviously, and start seeking customers.

Because Laravel was fun to work with, it made me remember why I chose this industry in the first place - something I forgot while stuck in the shitty education system.

So I started working on small projects at night, reading about methodologies and best practice. I revisited OOP, moved on to object-oriented design and analysis, and read Uncle Bob's book Clean Code.

This helped me realize that I really knew nothing. I did not know how to build software THE RIGHT WAY. But at this point it was too late, and now I'm almost done. My code is not clean at all, just spaghetti code, a real pain to fix a bug, all the logic is in the controllers, and there is little object oriented design.

I'm having this persistent thought that I have to rewrite the whole project. However, I can't do it... They keep asking when is it going to be all done.

I can not imagine this code deployed on a server. Plus I still know nothing about code efficiency and the web application's performance.

On one hand, the company is waiting for the product and can not wait anymore. On the other hand I can't see myself going any further with the actual code. I could finish up, wrap it up and deploy, but god only knows what might happen when people start using it.

Do I rewrite, or just keep trying to ship, or is there another option that I've missed?

答:
To answer your question: as so many others have said, no. Ship it, and clean it up bit by bit in the process of fixing bugs.

Additionally, while books/StackExchange/webforums are good learning resources, you are likely to find that nothing can match the learning you will receive from working (or even just discussing work) with other programmers. Finding and attending a local group for a technology you are using or would like to learn is a wonderful investment of your time. Besides the technical knowledge to be acquired, it's an easy way to network which is invaluable as you look forward to future gigs.


问:
Is there a specific reason that dingbat fonts are supported or ever even created?
I have known about the weird dingbat fonts since the first time I tried to change the font on MS word and stumbled upon them. Since then I never questioned them, I just thought hey cool. Now I have some questions.

What is the purpose behind creating dingbat fonts?

Is there anyone/entity that actually uses/needs these types of fonts?

答:
They provide symbols to use in documents. Looking at the link you provided, things like checkmarks and arrows are provided, so that you can insert those in places that they make sense.

They have since been replaced by unicode characters, which has given a lot of the more popular items their own character code, and that has been the widely accepted way of defining these symbols now.


答:
For reasons that others have thoroughly explained, it is time to finish the project and ship it, painful as that may be.

I would just like to emphasize that testing the app is also part of "finishing" it.
If significant pieces of functionality haven't been thoroughly exercised and correct
results confirmed, then you're justified in your concern that people will have
trouble with this app when it is deployed.

Unit tests and automated higher-level tests are great and are things you should have as much as you can before you try to refactor (or rewrite) this application. But right now you mainly need to test it, even if you have to run every test "by hand" and confirm the correct functioning "by eye". If you can figure out how to automate those tests later, that will help when it's time to start work on the next version of the product.

Some people have a knack for sitting down in front of a new software project as an alpha-test user and making things go wrong. That is, they're good at breaking things. If you are lucky enough to have such a talented person working with you, let them try the app first so you have a chance to fix any obvious bugs early.
If you have to do this task yourself, then:

Be methodical.

Try every feature.

Pretend you're a user inexperienced with your application. Make stupid mistakes and see how the software handles them.

Write down what you're doing so you can try it again after you think you've fixed the problems.


问:
Nested maps vs. combined keys
in the project I am currently working on we had three different types of prices depending on the age of the user (adult, child, etc...). So we had on the DB a table looking like this:

PRICES
type     Amount
A         20
B         15
C         ..
D         ..
```
</blockquote>

<p>At first we only had 4 different types of prices, so in the code, we had something like this:</p>

<pre class="lang-none prettyprint-override"><code>Map<String, BigDecimal> prices = new HashMap<String, BigDecimal>();
</code>```

Where the keys were the price type.

Recently, they added a new business rule that adds 3 subtypes to every price type, so now we have something like this:

PRICES
type   subtype  Amount
A          1      20
A          2      15
A          3      ..
B          1      ..
B          2      ..
...        ..     ..
```
</blockquote>

<p><strong>Which of the following two options do you think is better and why?</strong></p>

<h1>Nested Maps</h1>

<pre class="lang-java prettyprint-override"><code>Map<String, Map<String, BigDecimal>> prices;
</code>```

where the keys are the price type and subtype:

prices.get(type).get(subtype);
```

<h1>Combined Keys</h1>

<p>The same map than originally:</p>

<pre class="lang-java prettyprint-override"><code>Map<String, BigDecimal> prices;
</code>```

And concatenate the keys to index the different prices:

prices.get(type+"_"+subtype);
```

答:
Both options are not good in my opinion.
Say what if the business logic changes again so that you have another subtype?

What I suggest you do is the following:

Use a surrogate key for a table call Type this table would look like Type(INT auto_inc id, VARCHAR(255) name, VARCHAR(255) desc, INT status, etc)

In your Price table use foreign key to the Type table above so it would look like Price(INT type_id, INT price)

Make sure you do NOT support deleting a type. You simply mark a type as inactive because of the dangling references would make deletion a real headache

Now, user and business logic can add whatever type subtype combination into the schema. What they would need to do is simply creating new row in the Type table and changing name and/or desc in the old table.

In your case, user would rename type A to type A_1, add a new type called A_2 and set new price for A_2 as 15

Title: Nested maps vs. combined keys


问:
Static vs. non-static? (with non-OOP functions)
Although this question has come up before, mine is different because it is not supposed to cover anything OOP but only plain (ANSI) C.

Especially in open-source software, I usually encounter a plethora of functions (please don't call them methods since we're not in OOP) with the static keyword preceding the data type.

But what effect does this actually have with plain C? In my own projects, I've never had an occasion where the static keyword was actually needed. (Although a so-called expert programmer would probably have given me the advice, "This function should be declared static" and I would probably have replied in my own sarcastic way: "Uh-huh. Well, it works as-is, after all". :)).

From reading the OSS code, I assumed it might just generate less overhead when compiling the project. However, CPU have advanced in performance so much that I've wondered many times why there is such an ongoing interest to declare functions static even though it might need some benchmark tool to measure the differences in execution speed.

答:
"Static" is overloaded to mean two things in C:

At the file level, it restricts scope to the current file. (I think this is what you're seeing.)

Within a function, it transforms variables such that their values are preserved between calls.

"Static" has little to do with performance in C. In the context in which you saw it used, it relates to scope-of-access. In this usage, "static" actually ends up being similar in function to access modifiers in an OOP language than with the "static" keyword as it applies to C++ methods.


答:
The keyword "static" in Java just means objects of that class are not tied to the enclosing class.  It has nothing to do with static methods and fields.  A static class is even more normal than a normal Java nested class.

You may be thinking in terms of the C# static class, which does not allow state, and contains only static members.  (C# is a bit more consistent with the term.)  I have heard people, even when talking about Java, refer to classes with no state as "static", so it pays to check what people mean when they use the term.

If you are familiar with C#, be aware that, deep down, Java and C# are very different languages, and their superficial similarities will trip you up badly if you're not careful.