答:
See also the ABI specification and the calling conventions for your target platform. For x86-64/Linux, read the x86-64 ABI supplement (see also the x86 calling conventions wikipage).

Several aspects of <stdarg.h> are built in the GCC compiler (e.g. thru __builtin_va_start,  __builtin_va_arg, etc...) and <stdarg.h> is provided by the compiler. See also its __builtin_va_arg_pack, etc...

You might also be interested by libffi (e.g. if you want to dynamically build a call to a variadic function).

Title: What is the underlying mechanism behind va_list and where is it defined?

Body:
http://www.cplusplus.com/reference/cstdarg/va_list/
According to the above link, va_list is an argument or parameter used in some macros - va_start, va_arg, va_end. These macros are present in the stdarg.h file.

I know that va_list can hold multiple values but what kind of an entity is va_list? My question is what is the underlying mechanism behind va_list? How is it able to hold multiple values? (For example, an array can hold multiple values and the mechanism behind it is multiple memory locations referenced by subscript values. Array is a predefined data structure present in C.)

My second question is where is va_list defined?


问:
How to operate a computer without an operating system?
How a computer can be used when there is no operating system?

What tools or knowledge do I need to do it?

Do I have to give all the commands in binary to use computer hardware resources like a monitor?

答:
It is possible to write code without any OS, put it on hard drive, optical drive or USB drive, at specific address and run it. It's also possible to run such code from the network (network boot option).

Also it is possible to run code like an extension BIOS, well, in fact CPU juts jumps to user code and neither BIOS nor OS works but user code does.

Here are examples of some Russian security PCI boards, which run its own program before any OS can take a control. The boards, shortly, serve for indentfication and authentication  users and run graphical interfaces, can operate with file systems, etc.

Sobol PAK

Crypton zamok

ContentLicense: CC BY-SA 3.0


问:
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?

答:
Every project leaves you smarter than you were before. After every project you will have accumulated more experience which would have been very handy when you had it from the start. I know that it is hard to not revisit everything and apply what you have learned. But remember:

Perfect is the enemy of good.

For the client it is always better to have a good software now than a perfect software which will never get released.

This was just your first project. There will be many more projects in the future where you can apply everything you have learned from the start.


问:
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

答: It is whatever you want it to be.  I tend to use year.month.day.hhmm for my major.minor.build.revision.  If I'm producing more than one a minute, something's wrong.  you can just use a simple increment, or I've seen some elaborate generators for them.  What do you want it to be.  What they need to do is make it so you get to the source used to create that output, so whatever enables you to do that.

ContentLicense: CC BY-SA 2.5


问:
If a dependency is not in the maven repository should I add it to source control?
One of the jar files that I use in my code is not in the maven repository(and yes I tried to avoid using it). I have installed it locally so when I build the project it gets picked up by maven. I also put instructions in my README so anyone who wants to build my code can see how to add the jar to their local repository.

The question is, should I check this jar into my git source control?

I know normally you don’t check jars into source when using maven and git but in this case it seems like it might be a better idea than saying, find this jar on the internet.

I am the only developer in my group so setting up a company hosted repository for just this single jar is overkill.

答:
If it is just a single JAR file, then I don't think version controlling it will be apocalyptic.

If however, you start adding more and more external JAR files to your app, then you should consider using a repo manager like artifactory to deal with this whether you opt to use Gradle/Maven/ANT.

If you have a build script, you can further simplify the task of building the app by automating the process of checking out the JAR from GIT and making it available.  This might be a little easier as it puts the onus on you, the author, to manage the dependency opposed to the library user. You can also upgrade the library behind the scenes without the user being aware of it (unless there is no network connection..).


问:
Does it make sense to use interfaces if you don't have polymorphism?
Suppose I have distinct classes that have the same behavior, which can be represented like this:

```<code>public interface Behavior {
    void operationA();
}

public class ImplementerA implements Behavior {
    public void operationA() {

    }
}

public class ImplementerB implements Behavior {
    public void operationA() {

    }
}
</code>```

But ImplementerA and ImplementerB are used by distinct clients; ClientA only uses ImplementerA and ClientB only use ImplementerB; other than these, there are no other clients for ImplementerA and ImplementerB.

In this scenario, does the interface Behavior have any purpose? Should it be created because maybe future requirements changes...

答:
If you're using a language where classes must be hard-coded into the code (e.g. Java/C#) then it might make sense to use an interface in case you ever want to change the implementation of Behavior that gets passed to ClientA or ClientB without recompiling. This usually happens when you want to unit test some code by providing mock implementations of Behavior. Without an interface you'd have to change the import statement of the client code so that it references the right implementation and recompile it.

In languages that don't hard-code references to classes using globally-unique identifiers (which is what fully-qualified names such as com.yoursite.Foo are) this isn't an issue and there's no need to make an interface. However languages with this kind of module system are relatively unpopular functional languages (e.g. Standard ML, OCaml) so it likely doesn't apply to you.

Note, however, that not every class can be implemented as an interface. Consider:

```<code>public class LooksAtOthers {
    public LooksAtOthers binaryOperation(LooksAtOthers other) {
        ...
    }
}
</code>```

The binary operation here looks at the private fields of other. This comes up a lot when implementing data structures; in order to do efficient merges or unions you have to be able to look at the implementation of both operands. This can't be done from an interface:

```<code>public interface CantLook {
    CantLook binaryOperation(CantLook other)
}

public class CantLookImpl implements CantLook {
    public CantLook binaryOperation(CantLook other) {
        // no idea what type CantLook has
    }
}
</code>```

Here CantLook is an interface, so the class implementing CantLook has no idea what private fields other has. As a result if binaryOperation required looking inside other, it can't be implemented efficiently any more.

Note also that using a class makes debugging somewhat easier. With a class any given client code only interacts with one implementation; it either works or it doesn't. With an interface there can be any number of implementations and nothing stops someone from making a bad one. If you use an interface and ClientA breaks, you have to look at which implementation of Behavior broke it. Someone might've created and passed in a buggy ImplementerC.

So the bottom line is: it depends. Does it bother you to have to change import statements? Are you doing unit testing? Do you need to look at other instances of the class?

Body:
If you're using a language where classes must be hard-coded into the code (e.g. Java/C#) then it might make sense to use an interface in case you ever want to change the implementation of Behavior that gets passed to ClientA or ClientB without recompiling. This usually happens when you want to unit test some code by providing mock implementations of Behavior. Without an interface you'd have to change the import statement of the client code so that it references the right implementation and recompile it.

In languages that don't hard-code references to classes using globally-unique identifiers (which is what fully-qualified names such as com.yoursite.Foo are) this isn't an issue and there's no need to make an interface. However languages with this kind of module system are relatively unpopular functional languages (e.g. Standard ML, OCaml) so it likely doesn't apply to you.

Note, however, that not every class can be implemented as an interface. Consider:

public class LooksAtOthers {
    public LooksAtOthers binaryOperation(LooksAtOthers other) {
        ...
    }
}

The binary operation here looks at the private fields of other. This comes up a lot when implementing data structures; in order to do efficient merges or unions you have to be able to look at the implementation of both operands. This can't be done from an interface:

public interface CantLook {
    CantLook binaryOperation(CantLook other)
}

public class CantLookImpl implements CantLook {
    public CantLook binaryOperation(CantLook other) {
        // no idea what type CantLook has
    }
}

Here CantLook is an interface, so the class implementing CantLook has no idea what private fields other has. As a result if binaryOperation required looking inside other, it can't be implemented efficiently any more.

Note also that using a class makes debugging somewhat easier. With a class any given client code only interacts with one implementation; it either works or it doesn't. With an interface there can be any number of implementations and nothing stops someone from making a bad one. If you use an interface and ClientA breaks, you have to look at which implementation of Behavior broke it. Someone might've created and passed in a buggy ImplementerC.

So the bottom line is: it depends. Does it bother you to have to change import statements? Are you doing unit testing? Do you need to look at other instances of the class?


答:
The main reason to use interfaces is explained in the dependency inversion principle ( the D in SOLID ).

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

Abstractions should not depend on details. Details should depend on abstractions(***).

The goal of this is decoupling the higher level from specific implementations, allowing for more maintainability.

Maintainability's main issue is compensate the unability of human beings to foresee the future.

Statements like "ClientA only uses ImplementerA and ClientB only use ImplementerB" has proven to not hold true forever.

*** NOTE: In the context of SOLID and OOD, "abstration" means than it cannot be instantiated, like an abstract class or interface.

Something that cannot be instantiated needs to have very little reason to change overtime. That way code that depends on abstractions depend on things that are stable ( the what vs the how ). Code that depends on abstractions have less reason to change that code that depends on concretions.

Title: Does it make sense to use interfaces if you don't have polymorphism?

Body:
Suppose I have distinct classes that have the same behavior, which can be represented like this:

```<code>public interface Behavior {
    void operationA();
}

public class ImplementerA implements Behavior {
    public void operationA() {

    }
}

public class ImplementerB implements Behavior {
    public void operationA() {

    }
}
</code>```

But ImplementerA and ImplementerB are used by distinct clients; ClientA only uses ImplementerA and ClientB only use ImplementerB; other than these, there are no other clients for ImplementerA and ImplementerB.

In this scenario, does the interface Behavior have any purpose? Should it be created because maybe future requirements changes...


答: If you're really interested in the dilemma you have, you should also read "Lean Startup". A lot of the advice that you're being given here will resonate with you more if you read that book. Basically, resource burn-rate is your worst enemy and nothing is more valuable to you and your organization than end-user/customer feedback. So, get your product to a viable state (the Minimum Viable Product - or MVP) and then ship it out the door (regardless of what the code actually looks like). Let your customers dictate your future changesets and versions, not the other way around. If you focus on that approach both you and your boss will be happier in the long-run.

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?


答:
I [...] read Uncle's Bob clean code.

I'm having this persistent thought that I have to rewrite the whole
  project.

This book has a section named, very appropriately, "The Grand Redesign in the Sky".

Don't try to rewrite everything because, in the unlikely event that you have the time to make it, you will face the same problems anyway. When you have finished the redesign you will have learnt new things and will realize that the first parts of it are very unprofessional, so you will want to rewrite it again.

Redesign and rewriting are good, but only if they are done incrementally on a working system. As another user pointed out, follow the Boy Scout Rule, refactoring your code little by little as you work on it.


问:
Who creates the agile definition of done(DoD)?
I believe that the "Definition of Done" is created by the Team and the "Acceptance Criteria" is created by the Customer. Am I correct?

Can a customer define the Definition of Done to the agile team?

答:
I don't think it is quite as cut and dry as in smp7d's answer.

The Definition of Done is created by the team, but may require the Scrum Master to enforce quality constraints if the team don't have clear development standards.  For example, a team may not want code reviews or unit tests, but a Scrum Master may need to enforce them to ensure quality is maintained.  In the ideal situation the team see the benefits and want such quality constraints, but the real world isn't always ideal.

The acceptance criteria should be created by everyone but confirmed with the Product Owner.  For example the customer or PO may want the ability to log in, but the team add the acceptance criteria of security, performance etc.  Just like creating stories, everyone can come up with ideas but the Product Owner has the final say.

Some of these things may overlap. For example in our team rather than specifying acceptance criteria around performance in every story we have moved it into the Definition of Done.  A Definition of Done shouldn't be specific to a feature or story but should span at least a project, if not all development.


问:
What diagram would be the best to describe the situation
I am working on a software integrated with the hardware component. I need to create a simple diagram to express that:

Certain activity runs in a cycle (the device continously monitor a temperature)

When the temperature deviates from the baseline and remains so for 10 seconds, a function is called

I am writing a high level document and I am not sure how to capture this - UML diagrams do not seem to be suitable..but maybe an activity diagram?

答:
Either activity diagram or sequence diagram (they are pretty much two views of the same thing).

(EDIT: whoops in earlier text I was confusing correlation diagram with activity diagram; they are really similar. Either it's been too long, or else there are just too many damn diagrams available. ;) )

Sequence diagrams have notation for looping; the message that follows the deviation would just come right after the loop.

...

The boxes around an activity diagrams just become the boxes at the top of the sequence diagram. I used to really like activity diagrams, but came to find sequence diagrams easier to manage -- personal preference. BTW there's a good online tool for playing with sequence diagrams:
http://websequencediagrams.com

...

Also, you're describing a state machine, so a state diagram might also work well. The states are

initial

normal -- no deviation

alert -- deviation detected, but less than 10 seconds

trigger -- deviation detected for 10 seconds

...and then back to normal.

In any case, there are a few good choices. It's a small enough problem that you could do it each way and see what looks best.


问:
VB.NET - Serial Key Generating (Encryption, Hashing, Encoding?) Algorithm
I am trying to create a basic licensing system where I take a unique ID from the client computer, and I get this Hexadecimal string (hyphens removed e.g. "84-18-CE-...."):

"8418CFEE73FA22E6AB0760C73A496497C6C347DA88A9F63B95FE1E1D6A350AA1D7D3A9EE870795AECC3C109AA8B4A78C"

It's only encoded into this format to make the ID longer.

Basically what I've been trying to do (without success), is to create some routine that can transform this string into a 25-character long (minus the dashes) string like the one below:

"H8G02-J8293-L02O9-S920Q-F8D9X"

(An alpha-numeric key with numbers or letters in no particular pattern, preferably letter,number, letter or vice versa)

I just can't figure out how I could then validate this key, so that I could extract the untransformed Hex string we began with.

Note that the original Hex string will not always be the same length. Also, a routine that will convert ANY string into such a format (alpha-numeric, caps-only) will be acceptable.

I just realized that perhaps this isn't possible (to shorten the string down to 25 characters, and still retain the information (silly, I know). I will now accept anything that will allow me to create a 25-character OR LONGER string, from which I can select 25 characters.

答:
Convert the hexadecimal number to base 36.  Example here.

According to that page, Your input yields

1DWCLWKQZK16WMKIIEYVLLXA9E4OQ64P80KDOH4ALCYRCYCTKRUHQRXTM6HLDEV78E6APXQV1JG

in base 36.

Here is a Stack Overflow question that has an arbitrary base conversion function in c# (alas, couldn't get the online converter to properly convert it to VB).  You can see it in action here: http://ideone.com/nDun6s


问:
Wrapping constructor arguments
Given a base class with around 25 or so subclasses, I have found that adding an argument to the base constructor is painful.

```<code>protected AbstractController(Service1 s1, Service2 s2, Service3 s3){ ... }
public Concrete1Controller(Service1 s1, Service2 s2, Service3 s3) : base(s1, s2, s3)
public Concrete2Controller(Service1 s1, Service2 s2, Service3 s3) : base(s1, s2, s3)
</code>```

Now that I need yet another object passed to my base controller, I am debating introducing a wrapper class and refactoring so that only a single parameter is required in the constructors of (most) concrete instances.

```<code>public class ServiceLayer
{
    public Service1 S1 {get; private set; }
    public Service2 S2 {get; private set; }
    public Service3 S3 {get; private set; }

    public ScheduledReportServices(Service1 s1, Service2 s2, Service3 s3)
    {
        S1 = s1;
        S2 = s2;
        S3 = s3;
    }
}
</code>```

Which will allow me to clean up quite a bit.

```<code>protected AbstractController(ServiceLayer sl){ ... }
public Concrete1Controller(ServiceLayer sl) : base(sl)
public Concrete2Controller(ServiceLayer sl) : base(sl)
</code>```

Given the amount that this reduces clutter, I'm either a dope for not doing this to begin with or there's a valid argument against this kind of approach.

I'd be interested in a) knowing what this "pattern" is called and b) if I'm going to regret it and if so, why?

答:
There's nothing inherently wrong with this.  In the past, I've had several cases where it has been more logical to add a SomeClassCreateInfo class in to the picture, rather than passing parameters.

So when to do it?

This is an inherently more difficult question to answer, and it becomes largely situational.  Usually it becomes obvious when a Parameter-Wrapper/CreateInfo class is needed.  But also, sometimes, it might be a sign that things are wrong with the design.  In your case, the abstract controller needs access to a bunch of services.  Is there any other way to provide this information?

Title: Wrapping constructor arguments


答:
a) You are performing an 'Introduce/Extract Parameter Object' refactoring.

b) I cannot say if you will regret this or not. If every single instance of this requires services s1-s3 without exception, then this looks like a good refactoring.

This can open the gate to undesired dependencies if you are not careful with your parameter object. Try to avoid combining unrelated references going forward to prevent this from becoming a big dependency-ball.

Title: Wrapping constructor arguments

Body:
Given a base class with around 25 or so subclasses, I have found that adding an argument to the base constructor is painful.

```<code>protected AbstractController(Service1 s1, Service2 s2, Service3 s3){ ... }
public Concrete1Controller(Service1 s1, Service2 s2, Service3 s3) : base(s1, s2, s3)
public Concrete2Controller(Service1 s1, Service2 s2, Service3 s3) : base(s1, s2, s3)
</code>```

Now that I need yet another object passed to my base controller, I am debating introducing a wrapper class and refactoring so that only a single parameter is required in the constructors of (most) concrete instances.

```<code>public class ServiceLayer
{
    public Service1 S1 {get; private set; }
    public Service2 S2 {get; private set; }
    public Service3 S3 {get; private set; }

    public ScheduledReportServices(Service1 s1, Service2 s2, Service3 s3)
    {
        S1 = s1;
        S2 = s2;
        S3 = s3;
    }
}
</code>```

Which will allow me to clean up quite a bit.

```<code>protected AbstractController(ServiceLayer sl){ ... }
public Concrete1Controller(ServiceLayer sl) : base(sl)
public Concrete2Controller(ServiceLayer sl) : base(sl)
</code>```

Given the amount that this reduces clutter, I'm either a dope for not doing this to begin with or there's a valid argument against this kind of approach.

I'd be interested in a) knowing what this "pattern" is called and b) if I'm going to regret it and if so, why?


问:
Is it true: use Agile methodology results less planning?
I am kind of new in agile environment since I always participated in projects before which was only said to be agile while it wasn't.

Now I am really in an agile project and I see a setback - if it is setback - of agile methodology, the lack of pre-planning. I see that our BA talks to key users, collects data, which are pretty much just a sketch what they really want. Then we first need to refactor many of things because the real needs are a little bit different. Then there is a second phase when we realize they need a bigger system we expected, following that we need to make bigger refactor and generalize everything afterwards.

My questions are: Is this the way it should be? Given by the information are we doing it in the good way? And if the answer yes, then does the low planning costs match with the higher refactoring and rewriting costs? So to say: profitable?

答:
Then we first need to refactor many of things because the real needs are a little bit different

You are creating a false dilemma.

Real needs are almost always different than what users think/can tell you. Agile attempts to find these differences closer to when the code is written instead of at the end of a full project.

Agile is NOT "we will just start coding and see what happens." If you don't even know what features you are going to be working on for a sprint or they consistently change, have additions, or significant modifications all during the sprint, you are not really doing Agile development.

You need enough planning to be able to do a sprint without revisiting the requirements/user stories constantly. If this isn't happening, you aren't really using Agile appropriately.

This related question describes approximate planning times. You might find this useful. Additionally, this answer directly discusses planning for Agile.

Agile != no planning (contrary to many perspectives...).


答: Your boss was aware of your experience level when he hired you. Just express your concerns, and let him know you're nervous about it. Also let him know how much you've learned and how much better you can do the next project.</p>


问:
Is there a term for this coding practice?
One of the incidental complexities of introducing features to an existing system is that the programmer often has to touch several areas of code that are not immediately adjacent.  Over the long haul it can be unclear when looking at a bit of code that it pertains to another bit found elsewhere.  It's both ugly design and a maintenance hazard.  One of the properties of superior code, in my book, is its ability to keep a concept localized in one place.  Sometimes this is built in to an architecture up front making it easy to plug new features into a system.

In scripting languages where all classes remain open to extension at runtime, it can be easy to think of the language as its own platform and not go the route of formalizing how things plug in.  An app written in a scripting language could accept a module whereby the module reaches out to the various system components and changes them -- adding aspects to functions, wiring into events, and so on.  Essentially, because the architecture wasn't properly designed for extension, we utilize a poor-man's plug-in system and oftentimes this suffices.  In effect, we eliminate the need to modify several spots directly and instead tweak the system perhaps in similar spots but in an automated fashion.

That's what I'm focusing on.  We still need to modify things that are spread across our system, but we do so in a way that keeps the entirety of the change localized to a single file (module).

In there a design pattern/term for the practice of simply localizing all the code (even if it has tentacles) to a single physical location (its own file)?  I'm not sure it's the plug-in pattern or the extensibility pattern because in many cases a scripted system may not have been designed with extensibility in mind; however, it is still possible to localize change.  Would this simply be called modularity?  I'm really just looking for a shared term that I can use to rightly convey the concept without all the explanation.

答:
A design pattern is (to quote Wikipedia) "general reusable solution to a commonly occurring problem."  You're describing a characteristic of good code, not a particular solution to a problem, so "design pattern" doesn't really apply.

I believe the concept you're looking for is cohesion. Strictly speaking, cohesion refers how well the parts of a module belong together, but if changing a single piece of functionality requires touching several different modules, then cohesion must be lacking.

Separation of concerns is a related concept.

You might also be interested in reading about monkey patching (the ability of dynamic languages to extend classes at runtime, as you're describing; usually considered a bad idea, because it can so easily cause problems) and aspect-oriented programming (a more structured approach to putting cross-cutting concerns into a single module).


问:
Applying RESTful design to an entire website?
This all may come across very newbish, but I'm trying to wrap my head around designing a website that is thoroughly RESTful. I understand applying RESTful design to things like Users, Photos, Blog Posts, etc. because I think of them like "objects".

But, what about an "about us" page. What kind of resource is that? Is it even a resource in the RESTful sense of the word? Also, say I go to the URL "http://www.example.com/", what resource am I asking for? The index resource?

答: I would keep my view's independent of the back-end. You can ask the back-end for resources such as things that go on the accordion, the navigation bar, and other objects that pertain to the body. However, you should leave the processing of these resource representations to your client code, which will eventually render them as per the requirements. </p>


答:
Define "planning"

By "planning" I think you mean understanding the needs and figuring out how to do it, generally with a group of stakeholders (esp. users) and developers (et al). This involves a lot of conversations, thought, learning-time, etc.

Traditional methods try to plan too much to start, almost always with incomplete/unstable information.

Agile recognizes that information is incomplete (at any point in the project, but especially in the beginning), and so favors frequent, incremental conversations (and design/plan adaptations).

Assume that a certain volume V of communication is necessary to gain the mutual understanding necessary to properly plan and execute a project. How much V should be consumed up-front as opposed to in-process is subjective.

Personally, I like to consume just enough V up-front to get started; once everyone gets the basic idea/metaphor/goal and is excited about the project, jump into something with tangible value and show benefits - but with as many additional (but more focused) conversations as necessary.

Title: Is it true: use Agile methodology results less planning?

Body:
I am kind of new in agile environment since I always participated in projects before which was only said to be agile while it wasn't.

Now I am really in an agile project and I see a setback - if it is setback - of agile methodology, the lack of pre-planning. I see that our BA talks to key users, collects data, which are pretty much just a sketch what they really want. Then we first need to refactor many of things because the real needs are a little bit different. Then there is a second phase when we realize they need a bigger system we expected, following that we need to make bigger refactor and generalize everything afterwards.

My questions are: Is this the way it should be? Given by the information are we doing it in the good way? And if the answer yes, then does the low planning costs match with the higher refactoring and rewriting costs? So to say: profitable?


答:
The resource for "About Us" is ... Us :) er, You. Think about the attributes of You that you want to publicize, and roll those up as a noun with a representation.

Those values don't have to come from a database... it will probably be a bunch of string values, and those can come from config, or maybe even hard-coded in a class.

Title: Applying RESTful design to an entire website?

Body:
This all may come across very newbish, but I'm trying to wrap my head around designing a website that is thoroughly RESTful. I understand applying RESTful design to things like Users, Photos, Blog Posts, etc. because I think of them like "objects".

But, what about an "about us" page. What kind of resource is that? Is it even a resource in the RESTful sense of the word? Also, say I go to the URL "http://www.example.com/", what resource am I asking for? The index resource?


问:
Should special (simpler) cases have separate code paths?
I have a rather complex method which can get called in two possible "scenarios". One is a special case of the other in which all the nested foreach loops are only executed once and several if statements are false such that essentially only two lines of code nested deeply inside the method are actually executed.

Now the question is: Should I provide a separate (simpler) code path for the special case even though the complex code handles that case just as well?

I suppose the code would be more readable/understandable that way but I don't want to give the impression that the two cases are handled differently.

Performance is not an issue here so the fact that a simpler code path might also execute faster is negligible.

Example code:

```<code>foreach(...)
{
    foreach(...)
    {
    ...
        if(...)
        {
            ...
        }

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

as compared to

```<code>if(SpecialCase)
{
    Something();
}
else
{
    foreach(...)
    {
        foreach(...)
        {
        ...
            if(...)
            {
                ...
            }

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

答:
By essentially duplicating some logic you create redundancy. This is an opportunity for bugs.

I suppose the code would be more readable/understandable that way

No, because now readers have to understand one more thing than previously. They still have to understand the full algorithm to see what happens in case !SpecialCase.

I don't want to give the impression that the two cases are handled differently

Well, you are giving that impression. This is going to be confusing to others.

Consider just adding a comment:

"In case of SpecialCase the following algorithm is equivalent to Something();"


问:
As an API-user, would you tolerate BestPractice Exceptions?
I'm in the process of designing an API, part of which involves writing POCOs to a database.

In C#, we have the DateTime structure.  The "default" value for this (DateTime.MinValue) is 01/01/0001.

Part of the API serializes POCOs to the database.  If a date field is optional, it should really be nullable (in C# syntax, this would be defined as DateTime?).  What I'd like to avoid, is programmers falling in to the trap of writing DateTime.MinValue to the database at all.  It's a valid date, for sure - but smells of something.  So I am debating implementing a BestPracticeException class that would be thrown in circumstances such as this.

If the user of the API really needs to deal with that date, they probably also need to deal with dates prior to that and need an entirely different structure (e.g comparing how many months have occurred between 500 BC and today).

Do you think preventing writing 01/01/0001 to the database, on the whole, is a good thing to do?  One might argue that you need to differentiate between being no date entered, and the user entering nothing.  My answer to that would be it is the function of a more broader auditing process that would pick that up, rather than attempting to ascertain intent from a field being null, or not null.

答:
A date of 01/01/0001 would usually indicate a bug. Someone probably has used a default-initialized variable.

Your intention basically is to have a runtime assert to guard against a specific class of bugs. That's a valid thing to do. In fact it is done all the time.

Consider having this validation as a layer between the client and the storage API. Like this:

```<code>var date = GetDate();
Validate(date);
Store(date);
</code>```

Instead of:

```<code>void Store(DateTime dateTime) {
 Validate(dateTime);
 StoreImpl(dateTime);
}
</code>```

Let callers choose whether they want this validation or not. By convention, have most or even all callers perform the validation. This keeps the validation out of the storage system.

Body:
A date of 01/01/0001 would usually indicate a bug. Someone probably has used a default-initialized variable.

Your intention basically is to have a runtime assert to guard against a specific class of bugs. That's a valid thing to do. In fact it is done all the time.

Consider having this validation as a layer between the client and the storage API. Like this:

var date = GetDate();
Validate(date);
Store(date);

Instead of:

void Store(DateTime dateTime) {
 Validate(dateTime);
 StoreImpl(dateTime);
}

Let callers choose whether they want this validation or not. By convention, have most or even all callers perform the validation. This keeps the validation out of the storage system.


问:
Have there been studies on the effectiveness of OOP in managing software complexity?
OOP is often regarded as an effective strategy of managing complexity in software, as opposed to non-OOP procedural programming.

Have there been any studies testing this notion? Is it proven that OOP often helps manage complexity in large projects?

答:
Yeah there have been some studies.  Here's one:  http://www.csm.ornl.gov/~v8q/Homepage/Papers%20Old/spetep-%20printable.pdf

Basically it concludes that there's not a measurable difference between procedural code productivity and OO language productivity.... but the truth is, these types of questions are so context sensitive, no study is going to tell you what you should do in a given situation.


问:
How do you explain refactoring to a non-technical person?
How do you go about explaining refactoring (and technical debt) to a non-technical person (typically a PHB or customer)? ("What, it's going to cost me a month of your work with no visible difference?!")

UPDATE Thanks for all the answers so far, I think this list will provide several useful analogies to which we can point the appropriate people (though editing out references to PHBs may be wise!)

答:
Writing software is a lot like writing a big non-fiction book, or an encyclopedia.

The first draft always sucks.  It can always be improved by reorganizing it, removing sections that don't need to be there, and ensuring a consistent style throughout.

Whenever you have to revise, the simplest thing to do is just to add a new section, change a few words, and so on.  But as the revisions pile up, the book starts to lose its organization.  So you have to make further passes of reorganization.  If you don't, the book becomes a nonsensical jumble.


问:
When creating a library for a simple program, what must I do to protect others from its lack of thread safety?
When creating a library for a simple program, is it more cost effective to make it thread safe or is there a way to detect the program's use in a multithreaded program and ASSERT() or otherwise determine (preferably at compile or link time) that it may create problems.

Related help for this question would be automated tool support for finding potential problems with thread safety, programming language features that enforce it,

答:
The biggest thing I would suggest is that a class should consider void any contracts with callers that use it improperly, but improper usage by one caller should not affect the validity of contracts with other callers.

Suppose, for example, that a class implements "Popsicle Immunity" and promises that if IsFrozen returns true, all subsequent observations of any particular property will yield the same result.  Suppose further that one thread calls an instance's "Freeze" method while another thread is modifying that instance.  The threads modifying the object or calling Freeze have no legitimate expectations about what the object might do, but code elsewhere which calls IsFrozen, sees it return true, and observes some other property of the object would be entitled to expect that latter property would never change; the fact that the former methods abused the object should not weaken the latter code's right to expect that an object which claims to be immutable, is.


问:
Is it a good idea to "#define me (*this)"?
This macro can be defined in some global header, or better, as a compiler command line parameter:

```<code>#define me (*this)
</code>```

And some usage example:

some_header.h:

```<code>inline void Update()
{
    /* ... */
}
</code>```

main.cpp:

```<code>#include "some_header.h"

class A {
public:
    void SetX(int x)
    {
        me.x = x;
        me.Update();
    }

    void SomeOtherFunction()
    {
        ::Update();
    }

    /*
        100 or more lines
        ...
    */

    void Update()
    {
        // ...
    }

    int x;
};
</code>```

So in a class method when I access a class member, I am always using me, and when accessing a global identifier I always use ::. This gives the reader which is not familiar with the code (probably myself after a few months) localized information of what is accessed without the need to look somewhere else. I want to define me because I find using this-> everywhere too noisy and ugly. But can #define me (*this) be considered a good C++ practice? Are there some practical problematic points with the me macro? And if you as C++ programmer will be the reader of some code using the me macro, would you like it or not?

Edit: Because many people arguing not specificaly contra using me, but generaly contra explicit this. I think it may not be clear what are benefits of "explicit this everywhere".

What are benefits of "explicit this everywhere"?

As a reader of the code you have certainty what is accessed and you can concentrate on different things than verify - in some distant code - that is really accessed what you think is accessed.

You can use search function more specifically. Search "this->x" can give you more wanted results than only search "x"

When you are deleting or renaming some member, compiler reliably notifies you at places where is this member used. (Some global function can have same name and exist chance you can introduce error if you are not using explicit this).

When you are refactoring code and making non-member function from member (to make better encapsulation) explicit this shows you place which you must edit and you can easily replace this with pointer to instance of class given as non-member function parameter

Generally when you are changing code, there are more posibilities to errors when you are not using explicit this than when you are use explicit this everywhere.

Explicit this is less noisy than explicit „m_“ when you are acessing member from outside (object.member vs object.m_member) (thanks to @Kaz to spot this point)

Explicit this solves problem universaly for all members – attributes and methods, whereas „m_“ or other prefix is practicaly usable only for attributes.

I would like to polish and extend this list, tell me if you know about other advantages and use cases for explicit this everywhere.

答:
NO!

Just imagine the confusion that will occur if somebody #include's that header, not knowing your trick, and elsewhere in their file they have a variable or function called "me". They would be horribly confused by whatever inscrutable error message would be printed.


问:
Is there still any value in learning assembly languages today?
Specifically for a game programmer.

If you really needed some assembly routines you could look for help, whereas back in the 80s/90s it was one of the mainstream languages. I read that compilers can generally equal (or beat) most hand written assembly code, so unless you are an embedded programmer who can only program some device in assembly, for example, is there any real point in learning it nowadays?

答:
Assembly was never a mainstream language.  You learn it for the same reasons that people learned it in the 80s/90s, and before that: it's close to the metal.

Learning assembly language:

Teaches you how the machine works, and

Gives you access to the best possible performance (in theory).

I say "in theory," because it doesn't come without a cost.  Everything you get for free in higher level languages (math, I/O, some organizational structure) is a slog in assembly language, because you're literally building everything from scratch.

That's why, when assembly is used, you'll typically find it in specialized library methods and in inline code, while a higher-level language does most of the heavy lifting.  The assembly language optimizes that small bit of the code that will benefit the most from performance optimization.

Modern compilers give you most of the performance benefits of assembly language, without the cognitive cost.  But learning assembly still teaches you how the machine works at a deep level, and that knowledge will influence your software development long after you learn assembly, even if you never use assembly all that much.

If you do decide to learn assembly, I recommend that you learn it on an embedded device, like an Atmel AVR.  The number of opcodes to learn is smaller than a computer, and there's no operating system to worry about.


答:
BA talks to key users, collects data, which are pretty much just a
  sketch what they really want.

Do you feel the BA should spend more time, ask better questions, collect more data so you can plan out the entire strategy with little to no refactoring? Why don't the developers ask for more details before starting to code? Seems like there is a history here.

we realize they need a bigger system we expected, following that we
  need to make bigger refactor and generalize everything afterwards.

Do some sort of retrospective and determine if these things could have been identified sooner rather than later. You may find out that no one expected this at all.

Is this the way it should be?

I don't know about "should be" but this is usually the way it is and agile is a way to handle it better. How would you feel if you spent more time gathering incomplete specs, spent months writing code, and then having to rewrite all of that? This sounds even worse.

Given by the information are we doing it in the good way? And if the
  answer yes, then does the low planning costs match with the higher
  refactoring and rewriting costs? So to say: profitable?

You need to understand why "real" requirements aren't getting recognized until after some development has taken place (It's not that uncommon.). Maybe the BA can gather more or maybe you need to ask more questions and have him go back to the clients for details.

Sometimes you have to build something and get it in front of the clients so they can then determine what they really want. Few can do it in the abstract. Don't expect to double your upfront planning and cut your development in half. You'll probably find yourself making more detailed plans that just get thrown away because many places don't take the time to rewrite them due to falling behind.


答:
I would argue Agile (in my case agile scrum) is actually deferred planning compared to waterfall. The difference is agile planning I personally feel is your large scale plan is fuzzy / not detailed yet, but your short term plan is planned to extreme detail. As apposed to Waterfall where traditionally you planned the entire project up front (to the extent you could realistically do so)

Agile planning

Agile itself can be broken up into tons of sub methodologies, but at the highest level it's having detailed plans for short time spans 1 week to 1 month, past that is really pushing it. Your longer term plans more than 1 month down the road typically are not planned into much detail (yet) and live as list of features, bugs, etc to be done some day in your backlog.

The planning of your short term "sprint" is very detailed. You plan out the entire sprint, who will do what, technical details, etc. The precision of these plans vary team to team, but generally speaking successful shops tend to air on the side of more planning than less. The end of your sprint is your deadline, all work listed should be done by then (exceptions apply)

Typically you list all your want / need to haves in a backlog, each sprint you start at the most important items divvy them out you your team until you've assigned to the point they'll be kept busy, while still realistically finishing on time.

You repeat this process every sprint. This makes planning progressive so as the situation of the project changes the project can adapt.

Traditionally waterfall you planned everything up front and spent 3,6, or 12 months pounding it all out, Then going back and adjusting things at the end.

one way to think of agile is it's still waterfall, only your releases are weekly not annually. (someone will not be happy I said that, my point is you still plan things through just the scale of the plan is WAY smaller, but more often.)


答:
Violating a best practice is not an exceptional condition.  If you want to declare that 01/01/0001 is an invalid value, then throw an exception for that, specifically.

Looking forward to the day when my IDE throws an InvalidBraceStyleException.

Title: As an API-user, would you tolerate BestPractice Exceptions?

Body:
I'm in the process of designing an API, part of which involves writing POCOs to a database.

In C#, we have the DateTime structure.  The "default" value for this (DateTime.MinValue) is 01/01/0001.

Part of the API serializes POCOs to the database.  If a date field is optional, it should really be nullable (in C# syntax, this would be defined as DateTime?).  What I'd like to avoid, is programmers falling in to the trap of writing DateTime.MinValue to the database at all.  It's a valid date, for sure - but smells of something.  So I am debating implementing a BestPracticeException class that would be thrown in circumstances such as this.

If the user of the API really needs to deal with that date, they probably also need to deal with dates prior to that and need an entirely different structure (e.g comparing how many months have occurred between 500 BC and today).

Do you think preventing writing 01/01/0001 to the database, on the whole, is a good thing to do?  One might argue that you need to differentiate between being no date entered, and the user entering nothing.  My answer to that would be it is the function of a more broader auditing process that would pick that up, rather than attempting to ascertain intent from a field being null, or not null.


问:
Which (programming) specialities are needed in a good web development team?
At first glance, I'd say a good programming team needs to understand the following matters:

The details of the core language / framework

HTML, (asynchronous) javascript

SQL / data model

Usability / UI design

Security

Project management.

If this team is not complete: what is needed?

答:
Customer (or an advocate of some sort).

Basically, someone that can say, "Yes, you're building what I want and it's going to solve my problem." or that the team can go to when they have questions about how something is supposed to work.  That may or may not be the same person that is doing Project Management.

Also, you're missing out on a QA person there.  You can't really depend on the developers to adequately test - they're usually too close to the code and the normal response for developers is to test happy path stuff, not doing weird crap like copy pasting War & Peace into a textbox and seeing what the application does.


问:
Is SourceSafe really safe?
Having spent all morning trying to check something in - I now realise I've lost a couple of days worth of work.

Its happened before - and is apparently common occurrence with SourceSafe.  Can SourceSafe be used successfully, without problems, and if so, how?

答:
its default locking was slowing developers down, and no one wanted to mess with its setup

it doesn't integrate with other services very well, for example a project management web application

it was not going to work well with our planned CI server

The new 2010 Team Foundation stuff was supposed to help a lot, and try to get away from the bad parts of VSS. But at its core it still relies on VSS, which is why we moved to SVN.

edit - I understand that TFS is all new, but when testing it, multiple developers I asked had very similar feelings to it. The reason I said 'at its core' was because I remember looking at the files TFS made in my solution that looked just like those VSS made. This is from a developer standpoint, maybe not even knowing about the tech behind VSS or TFS or any other SCM. Sorry for any confusion.

Title: Is SourceSafe really safe?


答:
I think one of the values of assembly languages today that is often overlooked is the didactic value. I would contend that an assembly language is the best entry language for someone who has never programmed before. Why? Because it is simple and bare. In assembly you have basically three elements: Registers, opcodes and memory addresses. Learn how to mix-and-match those three basic elements and you can do a lot. Now take C for instance, for someone who has never coded before, C is pretty darn complex. Right out of the bat you have functions, #includes, macros, structs and more. That's a lot to take in. Go to a higher level language like Java and then you have the whole concept of classes and objects that must be understood beforehand. My personal opinion is that when learning something new, I prefer to start small. This is why I think assembly is an overlooked didactic tool.

Now on practical aspects, when you get the job of optimizing code, there is also value in being able to read and understand assembly. A lot of optimizations are about reading compiled code and seeing where the compiler is screwing up and how to change your higher level code in a way to allow the compiler to generate faster machine code.

Specifically on game programming, if you look back at the 80s and 90s, there was a lot of assembly programming going on on games and other high performance software, mainly because it was a pressing necessity. Most games used assembly code to be able to access special hardware features, like vectorization instructions such as MMX/SSE/AltiVec/etc. Today, these vectorization instructions are available as compiler intrinsics, so there is little gain in writing them using assembly.

Another issue that is driving game programmers away from assembly is portability. Not many studios can afford to release their games on a single platform these days. You need to write portable code, so assembly is only used as a last resort.

Last-gen Consoles like the PS3 still saw quite a bit of assembly programming, mainly due to its special hardware features that could not be accessed in any other way. But next-gen hardware is a lot closer to desktop PCs in architecture and performance, so again, assembly is loosing space there.

Title: Is there still any value in learning assembly languages today?

Body:
Specifically for a game programmer.

If you really needed some assembly routines you could look for help, whereas back in the 80s/90s it was one of the mainstream languages. I read that compilers can generally equal (or beat) most hand written assembly code, so unless you are an embedded programmer who can only program some device in assembly, for example, is there any real point in learning it nowadays?


答:
I've been doing agile for years now - the one any only answer to your question is : "yes".

Agile development results in somethinh between little and next to no planning at all - it has its focus on flexible, customer-bound solutions - actually planning the solution strips the flexibility / agility away nigh-completely because the customer is bound to his own specifications and stories.

It is a somewhat "chaotic" process - although not really; solutions are implemented in a strictly pre-set environment which bends according to rules of flexibility / agility, scrum (for example) has no planning at all (if you dont count sprint planning), but the process of change can only happen via teamwork, strategic and tactial planning and large amounts of user-feedback. In the result, the team will have implemented a highly functional, highly user-compliant solution in even less time than other processes / frameworks facilitate... if carried out correctly (you will need a highly competent team) the lack of planning does next to no harm, only minor drawbacks are to be expected which are very manageable and can be eliminated over time with little effort.


问:
Cannot explain to the customer that he is taking the project wrong way
Being a junior developer in need of some money for new hardware, I have stumbled upon many of the freelancing websites, and really soon, I have gotten my first customer. Complete Project Management, CRM and simple accounting website for small business. As we have been discussing the terms, I have proposed GAE/Python/Bootstrap/NDB as that is something I am really familiar with, as I have been working on GAE projects for the past two years at my internship place. We discuss the pay, terms, non-disclosure and I offer my approach to the project (followed the path of what I learned closely).

I propose working on the backend first in three phases:

Company/User System + Project management

CRM

Analytic/Simple Accounting (intuit integration as he later added)

I followed up with a 2 week period of the UI developing and testing.

At first I have asked him, what are the functions you would like me to develop in all the three phases. His reply was that he doesn't have the time to prepare the document I asked him for, which I found ridiculous, and asked me to prepare one and he will edit it. Of course he never did edit. Okay, first sign of the client that doesn't have a clear picture of what he wants.

He bought a template and asked when do we start testing. So I deployed the app with just PM and Company/User login after two weeks, only to be told he cannot test on anything that is not that template. I made a replica of the theme, literally, as we cannot use the stuff that the actual theme does have (fancy inbox, calendar etc)

I told to myself whatever. The first approach I took was to create a base.html and base-nav.html and extend them in other templates, in order for the code and other stuff to be tested easily. I did made this via bootstrap. He repeated he cannot test on that.

Now I am struggling with an html page that is 4 thousand line long I have to trim to create a base.html I will extend in other templates, with all the ridiculous amounts of static files that are completely unorganized in the template files and with a boss that wants to test. He doesn't even know what he wants to test.

I have sent screenshots, deployed the app, chatted daily, but it just isn't enough to convince him we should be focusing on the backend instead of the frontend first.

It's like building a car - first he wants to built the outside parts and limit the engine, instead of first building the engine then adjusting the outside to it.

Do you have any tips on how to approach this and resolve it?

template - http://www.keenthemes.com/preview/index.php?theme=metronic_admin

答:
Consider Joel's advice in The Iceberg Secret, Revealed.  Make the template look exactly as nice as how well the back-end is implemented, and provide all such screenshots and progress reports in this manner.  Use wire-frames, plain-text placeholders, and similar ugliness in place of missing or broken functionality.  Instead of telling your client, "it will take me X time to finish the backend," tell them, "I know this is ugly.  Getting this feature working properly will take X time."

The ideal is for your client to still test the flow even when looking at the ugly proto-type.  You might be able to work around this with mockups (that look right) and flow-charts, but if the client refuses to help you verify your flows, you might just be doomed.

Of course, it's somewhat too late to follow this advice.

In the future, consider using a contract to outline your client's and your own responsibilities in advance.  This will lose you some customers (mostly the difficult ones), but protects you from reaching a point where everyone is angry, you've spent twice as much time as you expected, and your client refuses to pay you for failing to satisfy them.


问:
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?

答:
Yes, you can code recursive functions as iterations.  It basically requires you to maintain the information manually that otherwise would have been taken care of by the method calling code generated by the compiler.

In other words, you need a stack where each entry is a structure containing the passed parameters and all the local variables.  You always work on the top-most entry on the stack.  If you need to call yourself, create a new entry and put on top of the stack.  When done take the topmost entry of the stack exposing the one below, and use the previously topmost entry to extract the return values and update the new topmost entry accordingly.

I suggest you study a compiler book to see how this is usually implemented in machine code.


答:
Of course there's value.  It just depends on whether the value is enough to offset the cost.

If you regularly program Kernel modules, device drivers or high-performance, lockless algorithms that rely on hardware-specific atomic primitives, then sometimes assembly language is your only choice.  If you want those sort of programming tasks to be available to you, the cost of learning assembly might be worth it.

If you're primarily a PHP developer making web-apps, and you're not interested in doing anything else, you probably have little use for assembly.

Still, learning it has value, in the sense that it will help put into perspective the sort of code you write at a higher level.  At the end of the day, despite all of our object-oriented, higher-order function wielding code, the programs we write ultimately compile into a stream of opcodes, mindlessly executed by a processor: load, store, load, store, cmp, jump, load, store, etc.

Learning assembly gives you perspective, and in that sense it has value.  But again, whether or not the value is worth the cost of learning probably depends on what type of programmer you want to be.


问:
Could submitting a Pull Request ever constitute accepting a Contributor Licence Agreement?
Some software projects have a Contributor Licence Agreement. The agreement could, for instance, assign copyright of 3rd-party contributions to the original project creator.  Could submitting a Pull Request on github ever constitute accepting such an agreement?</p>

答:
Contribution license agreements, are, for the most part, contracts.  A contract is binding only if a party assents (i.e. agrees) as indicated by any reasonable means.  Those means can include traditional approaches like signing a paper agreement, but also a "click-to-accept" mechanisms, sending an email saying "I agree," or, as mentioned here, submitting a pull request -- but only if it is reasonable in the circumstances to conclude that you actually agreed.  If the notice that you agree by submitting a pull request is buried somewhere and you shouldn't be expected to have seen it, or you don't have the opportunity to see it prior to making the request, you might be able to avoid being bound to the contract.  But if you were informed (such as by a prominent notice on the site) that submitting a pull request constituted agreement, and it's reasonable to expect that you would understand that the agreement applied, then yes, you would be bound.  This is a common sense question -- there is not much magic to it.

I am a lawyer practicing in IP licensing, but if you have questions about your specific case you should talk to a lawyer who represents you -- I am only talking about the general case.

I would be interested to know -- assuming this string is not too old at this point -- the examples you are referring to.  I found this string while searching for an example of a site that says a pull request constitutes agreement to a CLA.

I note that the question of what is a "work for hire" or a transfer of IP rights is a different question.  Most CLAs are neither.


答:
This is normal. The customer wants something that does this and that but isn't exactly sure of the best way to accomplish this and that. You are the expert, they are relying on you to fill in the missing pieces of their vision. You need to give them enough to work with so they can say, yes that's what I wanted. Usually that's a canned functioning UI prototype. So most certainly the UI should be the absolute 1st thing to work on.

Also, it is very naïve to believe that customers have the time to be intimately involved in all the details of a project or that they know exactly what they want. That's why they hired you. You drive the project. If they are too busy to give feedback then you tell them what you are doing and if they later want changes, then point back to this: "I'm implementing the user interface screens as defined here. Please review and provide any comments by COB July 18th.".  If they never got back to you then I take that as implicit approval and any changes later on will cost extra.

As for reviewing your UI. Usually it is best for you to give a demo rather than for you to expect the customer to play with your prototype and give feedback. If giving an in person demo is not possible then arrange a WebEx session or something similar.

Title: Cannot explain to the customer that he is taking the project wrong way

Body:
Being a junior developer in need of some money for new hardware, I have stumbled upon many of the freelancing websites, and really soon, I have gotten my first customer. Complete Project Management, CRM and simple accounting website for small business. As we have been discussing the terms, I have proposed GAE/Python/Bootstrap/NDB as that is something I am really familiar with, as I have been working on GAE projects for the past two years at my internship place. We discuss the pay, terms, non-disclosure and I offer my approach to the project (followed the path of what I learned closely).

I propose working on the backend first in three phases:

Company/User System + Project management

CRM

Analytic/Simple Accounting (intuit integration as he later added)

I followed up with a 2 week period of the UI developing and testing.

At first I have asked him, what are the functions you would like me to develop in all the three phases. His reply was that he doesn't have the time to prepare the document I asked him for, which I found ridiculous, and asked me to prepare one and he will edit it. Of course he never did edit. Okay, first sign of the client that doesn't have a clear picture of what he wants.

He bought a template and asked when do we start testing. So I deployed the app with just PM and Company/User login after two weeks, only to be told he cannot test on anything that is not that template. I made a replica of the theme, literally, as we cannot use the stuff that the actual theme does have (fancy inbox, calendar etc)

I told to myself whatever. The first approach I took was to create a base.html and base-nav.html and extend them in other templates, in order for the code and other stuff to be tested easily. I did made this via bootstrap. He repeated he cannot test on that.

Now I am struggling with an html page that is 4 thousand line long I have to trim to create a base.html I will extend in other templates, with all the ridiculous amounts of static files that are completely unorganized in the template files and with a boss that wants to test. He doesn't even know what he wants to test.

I have sent screenshots, deployed the app, chatted daily, but it just isn't enough to convince him we should be focusing on the backend instead of the frontend first.

It's like building a car - first he wants to built the outside parts and limit the engine, instead of first building the engine then adjusting the outside to it.

Do you have any tips on how to approach this and resolve it?

template - http://www.keenthemes.com/preview/index.php?theme=metronic_admin


答:
Agile doesn't mean no planning, or even less planning; but it can mean no planning phase in the project.

In a true Agile project, the team is always planning, but in smaller chunks. Every new piece of knowledge gained nudges 'the plan' in one way or another. The plan itself is fluid and accepting of change.

The problem is that there is a tendency to want to sit down and document the plan. The moment you do that, the plan becomes a little bit out of touch with reality, which is constantly changing. The more time you spend documenting the plan, the more out of touch it can become.

Agile recognizes this counter-intuitive fact, and tries to minimize planning when you least know what your users ultimately need (i.e. at the beginning of the project) and maximize the planning closer to when you know more (i.e. later in the project, as you're developing and getting feedback).  Agile also recognizes that in many cases, documentation of the plan is less useful/important than execution of the plan.

As such, Agile asks that you only spend just enough time and effort planning (and documenting the plan) to allow the project to move forward responsibly. Any more than that, and it's a waste.


问:
Programming with emacs instead of a debugger-integrated IDE
There's a question that might be deemed a duplicate of this one (I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?) but I don't think answers my question.

I usually program in C++ (not exactly to create GUIs so rather low-level) and I find myself comfortable with editing code into visual studio, compiling it and debugging it.

I know that all of this can be done in a linux/unix environment (even on Windows) as well, but I'm wondering how come that many low-level programmers are proficient with tools like emacs which I suppose hasn't any debugger integrated (no breakpoints setting, doing that with gdb seems pretty slow and really unhelpful).

How can they develop a complex software with a write-compile-debug cycle in such environments? Am I missing something? I doubt that they develop code in Eclipse, Qt Creator or Visual Studio and then get back to their textual tools.

答:
Emacs does some things much better than other editors:

Startup time. One of the most important features for an editor is startup time. With IDE you need to wait 30 seconds to get your project to open, and another 30 seconds every time you switch to another project. Emacs just starts up so fast that editing software is easy.

Multiple instances. There will be multiple copies of emacs running. Not just single ide, but multiple copies of the text editor.

Large files. You'll end up having large amounts of code in single file. If your editor breaks when it loads 20kloc file, it's useless.

Searching. Finding correct place inside your code needs to be easy. Right way to do this is proper searching from within current file.

Navigation. Beginning-of-file is one of the most important features.

Goto-line. When compiler gives you error, it has line number included. goto-line will allow you to type the line number and instantly find the correct place in the code.

Buffers.. Both header file and .cpp file needs to be visible at the same time. Multiple editor buffers with split-screen are essential for seeing the source code.

Loading new files. Switching between files is rare, but necessary feature.

Saving. If your editor loses the code if you simultaniously edit the file from two copies of the editor, its no good. Emacs saves the code correctly every time.

Text editors are not suitable for compiling, debugging your code. Instead, the following tools will do the trick:

Compiling will work with makefiles from the command prompt. Typing "make" in command prompt will do the trick.

Debugging will use gdb and valgrind. Both of them are useful for getting call stacks. Trying to do single-stepping through the code is just waste of time.

Version control with git.

Note that these are outside of integrated development environment.


问:
Programming for future use of interfaces
I have a colleague sitting next to me who designed an interface like this:

```<code>public interface IEventGetter {

    public List<FooType> getFooList(String fooName, Date start, Date end)
        throws Exception;
    ....

}
</code>```

The problem is, right now, we are not using this "end" parameter anywhere in our code, it's just there because we might have to use it some time in the future.

We are trying to convince him it's a bad idea to put parameters into interfaces that are of no use right now, but he keeps on insisting that a lot of work will have to be done if we implement the use of "end" date some time later and have to adapt all the code then.

Now, my question is, are there any sources that are handling a topic like this of "respected" coding gurus that we can link him to?

答:
I'm afraid your colleague may actually have a very valid point. Although his solution is actually not the best.

From his proposed interface it is clear that

```<code>public List<FooType> getFooList(String fooName, Date start, Date end) throws Exception;
</code>```

is returning instances found within an interval in time. If clients currently don't use the end parameter, that does not change the fact that they expect instances found within an interval in time. It just means that currently all clients use open ended intervals (from start to eternity)

So a better interface would be :

```<code>public List<FooType> getFooList(String fooName, Interval interval) throws Exception;
</code>```

If you supply interval with a static factory method :

```<code>public static Interval startingAt(Date start) { return new Interval(start, null); }
</code>```

then clients won't even feel the need to specify an end time.

At the same time your interface more correctly conveys what it does, since getFooList(String, Date) does not communicate that this deals with an interval.

Note that my suggestion follows from what the method currently does, not from what it should or might do in the future, and as such the YAGNI principle (which is very valid indeed) does not apply here.

OwnerDisplayName: sveri

Body:
I'm afraid your colleague may actually have a very valid point. Although his solution is actually not the best.

From his proposed interface it is clear that

public List<FooType> getFooList(String fooName, Date start, Date end) throws Exception;

is returning instances found within an interval in time. If clients currently don't use the end parameter, that does not change the fact that they expect instances found within an interval in time. It just means that currently all clients use open ended intervals (from start to eternity)

So a better interface would be :

public List<FooType> getFooList(String fooName, Interval interval) throws Exception;

If you supply interval with a static factory method :

public static Interval startingAt(Date start) { return new Interval(start, null); }

then clients won't even feel the need to specify an end time.

At the same time your interface more correctly conveys what it does, since getFooList(String, Date) does not communicate that this deals with an interval.

Note that my suggestion follows from what the method currently does, not from what it should or might do in the future, and as such the YAGNI principle (which is very valid indeed) does not apply here.


答:
I'm presently developing software for embedded systems and an occasional PC application.

I have the following applications open during coding and debugging:

XEmacs -- Has nice features that Eclipse doesn't.  Also doesn't force
a file tree on you.

Visual Studio -- Nice debugger.  Can write console programs to test
embedded functions.

Parasoft C/C++ Test -- A Static Analyzer built on the Eclipse frame
work.  Can edit can compile using the target compiler; but can't
access the JTAG debugger to the target device.

IAR EWARM -- IDE with capability to talk to a JTAGJet debugger to our
target platform.  Decent debugger, builds in the target processor's
tongue, but lacks the analysis of the static platform.

Command Window -- For running Coverity Static Analysis scripts.

Cygwin Terminal -- Unix has nice features like find and grep.

UltraEdit -- used to edit batch files; can print syntax highlighted
source code with line numbers to color printers!

PTC -- Code Management System for checking files in and out.

I can't find the "one true GUI", so I have multiple applications open.  I find Eclipse very nice for Java and a pain for C or C++.

I also grew up programming before the IDEs were invented.  So, one would edit the file, close the editor, then build using a command line system (like make).

A lot of GUIs I have looked at are trying to sell a company's tool chain set.  You either by all of the tools to get their good GUI or nothing.

In summary, I develop code by bouncing around in applications.  There is no complete IDE that contains all the functionality for programming an embedded system and has features that I like and few of the ones I dislike.

Title: Programming with emacs instead of a debugger-integrated IDE

Body:
There's a question that might be deemed a duplicate of this one (I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?) but I don't think answers my question.

I usually program in C++ (not exactly to create GUIs so rather low-level) and I find myself comfortable with editing code into visual studio, compiling it and debugging it.

I know that all of this can be done in a linux/unix environment (even on Windows) as well, but I'm wondering how come that many low-level programmers are proficient with tools like emacs which I suppose hasn't any debugger integrated (no breakpoints setting, doing that with gdb seems pretty slow and really unhelpful).

How can they develop a complex software with a write-compile-debug cycle in such environments? Am I missing something? I doubt that they develop code in Eclipse, Qt Creator or Visual Studio and then get back to their textual tools.


答:
Basically, sometimes you prefer things more tightly integrated and streamlined, sometimes you want looser integration with hopefully wider choice of parts.

Hint: source-level debugging is also available via gdb.

There are also various build systems, some possibly superior to, or more flexible / extensible than what is built into VS.

No doubt, having everything integrated is often convenient.

In different circumstances, you could benefit from an ability to run a debugger on a remote machine two firewalls away (via ssh), or on a tiny embedded system.

It is not impossible, of course, to integrate various tools into a scriptable editor; both Vim and Emacs have modes for interaction with various debuggers, build systems, version control systems, etc. Some prefer these other tools.

It is also possible, of course, to create some kind of remote debugging probe or an exotic VCS interface for an IDE (like VS). But this begins to become suspiciously similar to the approach above :)

The strong point of IDEs, to my mind, is superior source code handling: navigation, refactoring, validation, frameworks support, everything that having a properly indexed, AST-represented code base gives you.


问:
How to operate a computer without an operating system?
How a computer can be used when there is no operating system?

What tools or knowledge do I need to do it?

Do I have to give all the commands in binary to use computer hardware resources like a monitor?

答:
Computers don't need operating systems, regardless of language. (Computers run on native code whether an operating system exists or not.)

In embedded systems, there are two fundamental models:  1) Work completes in an interrupt and the remaining time is in a background loop.  2) Work completes in the background loop and interrupts are used for quick activities (such as incrementing timers and I/O).

There are cases where a processor executes code in its {read-only} memory, then shuts down.

Remember that Desktop PCs are not the only computers.  Microwave ovens, dishwashers and TV remotes all have computers in them; as well as modern cars.  Some platforms are too small to consider an operating system (like a microwave oven or dishwasher), while larger ones have Real-Time Operating Systems (RTOS) like printers and automobiles.

As far as tools go, you need a build system that can take a language and compile it to the processor of the target system.  You need to somehow get that executable into the platform.  A "remote" debugger would also be helpful.  These are the basic tools.  You can find them in a single IDE or your can get different pieces from different vendors.  In general, your tools depend on the target processor.  If your target platform is a PIC controller, then an IDE that builds programs for a Pentium processor is of no use to you.

Commands to the debugger or monitor in binary are ancient school.  Most "monitors" take commands through a terminal port and often include a "help" sections for when you forget the command list or syntax.  In modern times, binary is primarily used for setting and clearing bits in hardware registers or fields in tightly packed protocols.  Binary is not friendly and not efficient.  So in times of needing to produce code efficiently, binary has been pushed aside.


问:
Privilege (Access/Permission) Control for Hierarchial Structured Resource
Question: Is there any standard model or industry defacto implementation for modeling and implementing Access Control in (i.e.) a Document Management System?

Note: I studied a bit the security mechanism of Windows (which I do not want to use), and I saw Users and Groups and Policies.

But I can't understand:

1 - How a single policy object can contain all information about allowed/denied actions on a subject for all users and groups, at a specific moment of time.

2 - How multiple policies on a specific subject, merge into one to provide least possible access.

3 - What is the mechanism (data structures, database, caching, implementation) of hierarchical resources like folders? Those king of queries are usually slow.

答:
Yes there is.

There are two parts to this:

First of all there is an authorization model called attribute-based access control or ABAC. ABAC extends the capabilities of the more well-known role-based access control model or RBAC. RBAC is user-centric and doesn't cater for the use cases you have. ABAC can help you write policies that take into account user, resource, action, and context attributes e.g. a manager can edit the document he/she owns or a manager can view all the documents that are draft and belong to the same department.

Secondly, there is a standard called XACML (eXtensible Access Control Markup Language) which implements ABAC in a technology-neutral way. XACML defines:

an architecture with the notion of a policy enforcement point and policy decision point.

a request/response scheme

an attribute-based policy language

You can read more on both topics at:

NIST's ABAC reference site

OASIS XACML website


问:
Sanity check for design pattern used with an intricate calculation model
I am working on a project that generates technical brochures in batch. The 3rd party API that is being used expects POCOs with property names that match field names used in each of the brochure templates. The task I am seeking advice on is with the data source that will be used to populate these POCOs. The data is based on cascading calculations against a Domain Model. I originally entertained the idea of having the Domain be self-calculating, but there are so many calcs required that it seemed obvious to me this needed to be abstracted away.

I created some hypothetical code that closely mimics the design pattern in question, and I am open to any suggestions or reaffirmations as to whether I am approaching this correctly.

My primary concerns:

The constructor for the "AirplaneResultsContext" class, which injects itself to calculation classes which are also publicly exposed properties. Does this create recursive paths?

The possible occurrance of circular references with cascading calculation calls to various properties/methods in various other classes. Note that I am re-using most of the calculation logic (as was requested) but I can propose the need for it to be refactored if need be.

I noticed I used the word "Intricate", which is usually a telltale warning for code that needs to be abstracted out, but I am struggling to see how I can make this better.

The entity being calculated against. Picture this as an aggregate root for a larger domain model.

```<code>class Airplane : Entity<int>
{
    public double WingLength { get; set; }
    public double FuselageCircumference { get; set; }
    public double FuselageLength { get; set; }
    public double SeatWidth { get; set; }
    public double SeatDepth { get; set; }
    public double SeatHeight { get; set; }
    public double IsleWidth { get; set; }
    public double LegRoomArea { get; set; }
}
</code>```

The calculation context. The intent is for this object to be passed along as part of a batch process -- an abstract factory which consumes an interface represented by this context class and generates the POCO objects. Note that I also omitted the interfaces and abstract classes that would be used for different calculation strategies for brevity.

```<code>class AirplaneResultsContext
{
    public AirplaneResultsContext(Airplane airplane)
    {
        Airplane = airplane;
        Fuselage = new FuselageCalculator(this);
        Seating = new SeatingCalculator(this);
    }

    public Airplane Airplane { get; private set; }
    public FuselageCalculator Fuselage { get; private set; }
    public SeatingCalculator Seating { get; private set; }

    public double ComputeWidth()
    {
        return Airplane.WingLength*2 + Fuselage.ComputeDiameter();
    }
}
</code>```

Calculators. In my non-hypothetical project, these methods are private/protected, cached on the first call, and read back by read-only properties, but I only wanted to show a basic representation of some of the calculation complexity.

```<code>class SeatingCalculator
{
    private readonly AirplaneResultsContext _context;

    public SeatingCalculator(AirplaneResultsContext context)
    {
        _context = context;
    }

    public int ComputeNumberOfSeats()
    {
        double isleArea = _context.Airplane.IsleWidth* _context.Airplane.FuselageLength;
        double availableArea = (_context.Fuselage.ComputeDiameter()*_context.ComputeWidth()) - isleArea;
        double seatArea = _context.Airplane.SeatDepth * _context.Airplane.SeatWidth + _context.Airplane.LegRoomArea;

        return (int) Math.Floor(availableArea/seatArea);
    }
}
</code>```

```<code>class FuselageCalculator
{
    private readonly AirplaneResultsContext _context;

    public FuselageCalculator(AirplaneResultsContext context)
    {
        _context = context;
    }

    public double ComputeDiameter()
    {
        return Math.PI / _context.Airplane.FuselageCircumference;
    }
}
</code>```

答:
It can. If you expose your calculator to be called by other calculators is possible to nest them through poor design.

This seems to be the same question as #1

My recommendation for your design would be not to pass the context into your calculators. Any calculations which depend on multiple sub calculations should be properties of the context. Instead just pass in the airplane to the calculator.

My own personal style would be to not to call your calculators 'calculators' but treat them as domain objects (Fuselage, Cabin, Wing etc.) and expose properties, not methods (Diameter, not ComputeDiameter). Properties expose calculations, whereas methods perform operations (calculating and returning values, or changing state)

And FYI there is a stack exchange for code review @ I would recommend moving this to Code Review (https://codereview.stackexchange.com)


问:
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've been developing on embedded systems for a couple of decades, and have the same problem with a sensible naming.

I've seen many approachs, including mapping an overlay array of bytes and just using indexes (which does not solve the problem at all as endianness is not taken into account).

I eventually settled on MSB, MMSB, MLSB, LSB (where the extra M means "middle").

But really, anything at all that you do which is remotely sensible* will suffice.

*sensible in this sense means that there is a name with some kind of rationale behind it. Calling them bob and fred would not be sensible.


答:
I call them "bytes".

So does everyone I've worked with. Lacking a commonly used nomenclature, you either adopt a idiosyncratic scheme which no one else will understand, or you throw more words at it when you need to disambiguate.

Title: What are the bytes between the MSB and LSB named?

Body:
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>```


问:
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?

答:
I forget where I first read it, but I just wanted to echo, somewhat more forcefully, what other people have said:

Shipping is a feature.

There is nothing worse than that one guy who keeps "cleaning up" existing (possibly hacky, ugly, dirty) code that works perfectly well, introducing new bugs, etc. What matters in the real world is getting your job done. You've done that. Ship. Don't get lost in redesigns of a project that works perfectly well, even if it's ugly under the hood. When you fix it, do so incrementally, and make yourself a good test suite so that you have as few regressions as possible.


答:
Recursion is often a more natural way of looking at things than iteration.  For example, consider inorder traversal of a binary tree:  inorder(left); process(); inorder(right); is a lot simpler than explicitly maintaining a stack.

As long as you don't go too deep (blowing the stack), the difference in resource use is usually trivial.  Don't worry about it in general.  Simple code is normally better than hand-optimized code, although there are exceptions.  Right is normally better than fast.

Any recursive algorithm can be expressed as an iterative algorithm, but you may need to keep an explicit stack (corresponding to the call stack that's handled implicitly).  After all, if you compile a recursive function, you get something that relies on manipulating a stack and looping through the function, and that's iterative.

Tail-recursive functions can be easily translated into loops, and don't need a stack, but that's a special case.

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?