问:
What monad is the opposite of the error monad in haskell
In the error monad, the first failure halts any execution further just carrying the fault through any following binds.

What monad halts on success only carrying forward successes, and basically swallowing any faults and trying the next bind disregarding the failure of the previous one?

The error monad could maybe be used for this treating failure like success, but I'm curious if the default libraries have a monad for this specific purpose, almost like an Or monad in my mind "Do this, or that"

Edit:

Behaviour would be:

```<code>Left "fail" >>= (\x -> Right "win") >>= (\x -> Left "ahh neener") >>= (\x -> Right (x + " yay"))
</code>```

In the error monad the first left value is just carried forward, so the result of that is Left "fail". The behaviour I want is where the above returns Right "win yay" it's a trivial monad to implement I could write myself, but figured something existed to do such (maybe not using Either, but that's the first thing that comes to mind for such behaviour).

答:
What you need is MonadPlus (see also Haskell wiki). It defines

```<code>mzero :: m a
</code>```

which represents an unspecified error, and

```<code>mplus :: m a -> m a -> m a
</code>```

which tries the second computation, if the first one fails. A few auxiliary functions are provided too:

```<code>-- Extends `mplus` to lists of computations:
msum :: MonadPlus m => [m a] -> m a
-- Fails a computation conditionally.
guard :: MonadPlus m => Bool -> m ()
-- Filter (fail) computations that don't satisfy the predicate.
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a
</code>```

Instances of MonadPlus can be divided into two categories:

mplus combines all possible results from both its arguments (satisfies Left Distribution law). [] and Seq are probably the only instances with this behavior.

mplus selects the left argument, if it contains a valid value, otherwise it selects the right one (satisfies Left Catch law). Instances with this behavior are Maybe, Either, STM and IO.

(MonadPlus instance of Either used to be defined in Control.Monad.Error as

```<code>instance (Error e) => MonadPlus (Either e) where
    mzero            = Left noMsg
    Left _ `mplus` n = n
    m      `mplus` _ = m
</code>```

but for some reason it seems to be missing in the current version.)

See also MonadPlus on Wikibooks and MonadPlus definition for Haskell IO.

Body:
What you need is MonadPlus (see also Haskell wiki). It defines

mzero :: m a

which represents an unspecified error, and

mplus :: m a -> m a -> m a

which tries the second computation, if the first one fails. A few auxiliary functions are provided too:

-- Extends `mplus` to lists of computations:
msum :: MonadPlus m => [m a] -> m a
-- Fails a computation conditionally.
guard :: MonadPlus m => Bool -> m ()
-- Filter (fail) computations that don't satisfy the predicate.
mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a

Instances of MonadPlus can be divided into two categories:

mplus combines all possible results from both its arguments (satisfies Left Distribution law). [] and Seq are probably the only instances with this behavior.

mplus selects the left argument, if it contains a valid value, otherwise it selects the right one (satisfies Left Catch law). Instances with this behavior are Maybe, Either, STM and IO.

(MonadPlus instance of Either used to be defined in Control.Monad.Error as

instance (Error e) => MonadPlus (Either e) where
    mzero            = Left noMsg
    Left _ `mplus` n = n
    m      `mplus` _ = m

but for some reason it seems to be missing in the current version.)

See also MonadPlus on Wikibooks and MonadPlus definition for Haskell IO.


问:
Syndication feeds and show I bother with providing anything other than RSS 2
I'm creating a CMS and have lots of legacy code from other applications. I'm wondering should I bother providing other syndication formats except rss 2? I'm inclined to say no but was wondering what other peoples opinions were.</p>

答: I would say either RSS2 or Atom, pick one. Any modern reader should be able to handle either.</p>

ContentLicense: CC BY-SA 2.5


问:
What are the advantages of Scala's companion objects vs static methods?
Scala has no static-keyword, but instead has similar functionality through companion objects. Behind the scenes the companion objects are compiled to classes that have static methods, so all this is syntactic sugar. What are the advantages of this design choice? Disadvantages? Do other languanges have similar constructs?

答:
Companion objects are the first place searched for implicits, after that, scala looks at Predef and then in explicit "import" statements in that particular source file.

I'm not enough of a java dev to know whether the java language or libraries provide any comparable mechanism.

ContentLicense: CC BY-SA 3.0


问:
Function overloading? Yes or no
I'm developing a statically- and strongly-typed, compiled language, and I'm revisiting the idea of whether to include function overloading as a language feature. I realized that I'm a little bit biased, coming mainly from a C[++|#] background.

What are the most convincing arguments for and against including function overloading in a language?

EDIT: Is there nobody who has an opposing opinion?

Bertrand Meyer (creator of Eiffel back in 1985/1986) calls method overloading this: (source)

a vanity mechanism that brings nothing to the semantic power of an O-O language, but hampers readability and complicates everyone's task

Now those are some sweeping generalizations, but he's a smart guy, so I think it's safe to say he could back them up if he needed to. In fact, he almost had Brad Abrams (one of the CLSv1 developers) convinced that .NET shouldn't support method overloading. (source) That's some powerful stuff. Can anyone shed some light on his thoughts, and whether his viewpoint is still justified 25 years later?

答:
Use-case against implementing function overloading: 25 like-named methods that kind of do the same things but with completely different sets of arguments in a wide variety of patterns.

Use-case against not implementing function overloading: 5 similarly-named methods with very similar sets of types in the exact same pattern.

At the end of the day, I'm not looking forward to reading the docs for an API produced in either case.

But in one case it's about what users might do. In the other case it's what users must do because of a language restriction. IMO, it's better to at least allow for the possibility of program authors being smart enough to overload sensibly without creating ambiguity. When you slap their hands and take the option away you're basically guaranteeing ambiguity is going to happen. I'm more about trusting the user to do the right thing than assume they'll always do the wrong thing. In my experience, protectionism tends to lead to even worse behavior on the part of a language's community.

ContentLicense: CC BY-SA 4.0

Title: Function overloading? Yes or no


问:
Mostly produce output at programming job but don't learn anything
When I started working a programmer, I learned lots at first, on the job.  Although Ive been given more responsibility, which is good in a way, it is mostly in the form of increased workload. I havent had much time or energy left to learn anything much new day to day. Sometimes I have 1 hr of time and energy left at the end of the day to keep up, but I mostly just produce a lot of the same type of code. It does make sense to spend working hrs producing, since it's the reason why a programmer is  trained and hired. However, I am concerned about if Im falling behind as a programmer, by doing what I was hired for, even if not learning much new. Is this standard for most programmers? </p>

答:
In my opinion my job title does not say 'coding monkey', therefore I think it is ok to improve everywhere, not just coding. Furthermore I had a talk with the head of my department and I told him that I do read articles during work time and he was actually glad about that. So here is what I do:

First of all, start your day with reading some new stuff, articles and so on. I do that in the morning, because as you I am too exhausted in  the evening. Evaluate what you read and think about using it for your job.

Be a catalyst for change. Review your daily work and check which of your work-steps could be optimized. Some months ago I realized my team had problems with Acceptance Testing (late, brittle etc). Therefore I started to inform myself about that topic and used that knowledge to tackle these problems.

Improve your coding skills by doing pair programming and code reviews. Talk to your superior, maybe it is ok to make a coding kata once/twice a month with your colleagues.

Try to improve other skills. Your presentation skills by creating some form of a knowledge group within your company; your coaching skills by taking care of new employees or an intern.

...Contrary to what you might believe, merely doing your job every day
  doesn't qualify as real practice. Going to meetings isn't practising
  your people skills, and replying to mail isn't practising your
  typing...

I really recommend this article as it summarizes how to deal with being a programmer and further education.
As Robert J. already suggested take a look at 'The Pragmatic Programmer', but also take a look at 'The Passionate Programmer'.


问:
How to connect several (mobile) devices
I want to start a little project, where I want to connect several of my devices. Some are Android mobile devices, others are desktop devices like a PC or laptop. Furthermore I want keep the project as generic as possible. Means I want to share it, so other people can use it.

By connecting I mean send messages between them. My problem is, that I'am not sure what technology or architecture to use, and hope to get some advice from you. (I think this question is more about software architecture then gorilla vs. shark)

I have considered several approaches already. I looked at Google's Cloud Messaging, but that seems not to fit my requirements, where several users can register to send independent messages. It looks more like, sending from one master to several devices.

The next thing I thought about was something lile VLC did with its Android remote app, where the desktop application hosts something like a server to which the mobile app must connect. This seems to be limited to LAN and only fits to about 80% of my use cases.

Is there another approach which does not require something like a server who is aware of all clients, which has to seperate the user's devices and route the messages?

答:
You can use ZeroConf (a.k.a. Bonjour) to discover other devices on a local network and create an ad hoc network between them. If you want to be able to connect devices across larger networks, though, you're going to need a server with a fixed address so that all parties have some well-known address that they can connect to. Most devices (laptops, tablets, phones, etc.) don't have a fixed address, so they're often hard to find. Further, they're often behind firewalls which make them impossible to connect to even if you do know where to find them. Instead, each device needs to initiate the connection. Two devices obviously can't both initiate the same connection, but having them both connect to some server that relays messages between them solves the problem.

You also need to consider usability. You don't want to run background software that's constantly listening for connections on a mobile device simply because listening means that the WiFi radio has to be running, and keeping that radio running all the time is a quick way to kill your battery. You don't have that problem with a stationary server.

Title: How to connect several (mobile) devices


问:
Where to check that a function actually did what I told it to?
Consider this function intended to kill all running instances of a subprocess:

```<code>killAllFoobars()
{
    pids = getRunningFoobars();

    foreach ( pids as p ) {
        killOneFoobar(p);
    }

    return TRUE;
}
</code>```

Where should I check that in fact all Foobars were killed? Should killOneFoobar() check that its Foobar is now killed? Should killAllFoobars() check that there are no more running Foobars before returning TRUE (seems a bit disingenuous to return TRUE without checking). Should the function calling killAllFoobars() check?

Consider that the check is an expensive operation, so should not be done 'just whenever' but rather only when necessary.

答: If the expense of checking the kill of each foobar added up is equal to checking all of them, I would check in the deepest function, kill-one. If you were to reuse the kill-one function elsewhere it would be more accurate and useful. Also it consolidates your specific process logic into one function. </p>


问:
Difference between Pattern and Principle
What is the difference between Object Oriented Design Patterns and Principles? Are they different things? As far as I understood both of them try to achieve some common goal (e,g. flexibility). So can I say a pattern is a principle and vice versa?

Design Principle = SOLID (i.e. Dependency Inversion Principle)

Design Pattern = Gof (i.e. Abstract Factory Pattern)

答:
OO Design Principle—

OO principle is a set of guidelines that ensures OOP concept.
Based on the OOP concept, this defines ways to design better way, a better design.
The basic OO design principle is SOLID.

A Design pattern provides a general solution to a design problem.
Please note “design pattern” can be applied to noon object oriented word too. So A OO design patterns (OODPs) are those which provide a general solution to object oriented design based OO principle.
Design patterns are discovered, not invented.
There are several ways to define OODPs and most famous one is BSC [Behavioral Structural Creational].

Following is the link for detailed explanation.
http://techythought.wordpress.com/2013/01/21/design-principle-vs-ds-design-pattern-describing-oop-elements/

OwnerDisplayName: Chandi Gorom


问:
Understanding open and listening ports
I developed an app in Java (which is working perfectly; with this app you can scan TCP/UDP ports -for testing purposes only-), but meanwhile when I was writing the code I read several documentation (wiki) about sockets. I thought open port is mean, a protocol where the client/server can establish/bind a connection even if there are nothing on the server side which can handle/response data. I thought open port is mean (if there are no routers/firewalls) a protocol which is ready to be used.

I was testing my application on my local server machine, but at first I thought my application is not working. It was working, but there was no any software which could response to my queries. After I opened my APACHE server and I wrote a simple UDP server (which can handle/response to any query on a specific port) the application was able to find those ports.

I thought listening port is a port which is used and it's opened. What does listening port is meaning?

If I send UDP packets to a remote host and there are no closed ports (router or firewall) what happens to the packet? Does the data is written in the buffer? Or it simply ignores/denies the packet.

答:
Listening ports are used in servers. If you have an apache web server for example, it does not know in advance when it will be used. Listening means that it just waits (like a recepcionist in a hotel :) and it is ready to send an answer whenever a client program (a browser for example) requests it. The connection becomes open when a client connects to that port and a conversation begins.

If no program is listening on a port, and a client tries to connect, then the operating system will reject it.

Title: Understanding open and listening ports


问:
Is it better to create a stored procedure or entities to get to the data I need?
I just jumped into a new project with a new company using Entity Framework and ASP.NET MVC 4. I am no expert on Entity Framework, but I think I have a decent grasp of how to use it.

From what I can tell, my models should reflect a table in the database omitting the columns I don't need. Also, we can use stored procedures with Entity Framework, or an IoC to map the model.

I need to connect the relationship with two objects, whose relationship is pretty nested. I could create a stored procedure to do this or create a bunch of models (based on the tables in the database) and use an IoC configuration to have a table from the database for each model, then query the models in the repository layer for the data I need using Linq to Entities. Seems like I would have a lot of ".Include(x=>x.SomeModel)"

My question is: which option is better for maintenance and integration in the future of the project? A stored procedure or Linq to entities?

Or am I not understanding Entity Framework properly?

答:
I would recommend creating a view and creating a specific entity that maps to that view.

Technically you don't even need to create the view in the DB, you can model the query purely in the EDMX storage model, but that's a little more on the advanced side of things (e.g. not supported in GUI). That said, if you have the ability to create the view in the DB I would highly suggest it as you can provide more optimizations to the view at the SQL level if need be (e.g. indexes specific to the view, etc.).


答:
I think you've definitely got the gist of EF, that's a good question.

I would recommend that you go down the Linq to Entities option. Don't be afraid to use  .Include(x => x.a), and remember that because this joins on another table you'll want to  make sure your joins (foreign keys) have indexes on them. To me the maintenance benefit of the entity framework is being able to modify your table structure (add/move/rename columns) and then be able to re-compile your c# code and pickup what's broken - man, this would have saved me DAYS of fixing up stored procs a few years ago after making DB changes. If your logic is inside a stored proc then you don't get this benefit.

Only if your c# is starting to get too complicated to maintain would you consider using a stored proc to do the work, which might be better for maintenance purposes. Or if you're querying a database that can't be effectively used by the entity framework (compound foreign keys or something else).

Title: Is it better to create a stored procedure or entities to get to the data I need?

Body:
I just jumped into a new project with a new company using Entity Framework and ASP.NET MVC 4. I am no expert on Entity Framework, but I think I have a decent grasp of how to use it.

From what I can tell, my models should reflect a table in the database omitting the columns I don't need. Also, we can use stored procedures with Entity Framework, or an IoC to map the model.

I need to connect the relationship with two objects, whose relationship is pretty nested. I could create a stored procedure to do this or create a bunch of models (based on the tables in the database) and use an IoC configuration to have a table from the database for each model, then query the models in the repository layer for the data I need using Linq to Entities. Seems like I would have a lot of ".Include(x=>x.SomeModel)"

My question is: which option is better for maintenance and integration in the future of the project? A stored procedure or Linq to entities?

Or am I not understanding Entity Framework properly?


问:
Software has sub-part Apache v2 license and other sub-part GPL v2 license
Firstly I am sorry I do not fully understand about licensing. Thus I want to ask here for my curiosity about licensing things.

Here is the case. I build a WordPress theme that using underscores.me as its starter theme. It has GPL v2 license. And then I build the theme using Twitter Bootstrap. It has Apache v2 license.

I have been searching about both licenses. I found that Apache v2 is only compatible with GPL v3, not GPL v2.

What license can put to my code? Apache? GPl? Or I just can not release it because of Apache v2 and GPL 2 are incompatible? Finally, does it matter whether or not I modify the code?

答:
There is no way to license software that is the result of combining components that have Apache v2 license with and components that have GPL v2 license that does not contradict the terms of at least one of the licenses, even if you do not modify any of the components in either package.

The Apache Licensing discussion on GPL compatibility indicates that if you use software that is licensed under Apache v2, you must license that portion of your software under Apache v2. However, if you have also included software licensed under GPL v2, then your software is considered to be a derivative work, and you must release the entire software under GPL v2. But, since the Apache v2 license says that the portions covered by the Apache license must be released under Apache v2, you do not have permission to release it under GPL.

This is from the discussion in the Gnu FAQ section on incompatible licenses that says:

Only the copyright holders for the program can legally release their
  software under these terms. If you wrote the whole program yourself,
  then assuming your employer or school does not claim the copyright,
  you are the copyright holder—so you can authorize the exception. But
  if you want to use parts of other GPL-covered programs by other
  authors in your code, you cannot authorize the exception for them. You
  have to get the approval of the copyright holders of those programs.

However, nothing is stopping you from creating a website using a mix of GPL and Apache components. Both licenses permit you to use the software for derivative works and you do not need to license software you create to yourself in order to use it. The limitations the license impose are on copy and redistribution and sublicensing.

There are some related questions (with good answers) on the programmers stack exchange that may shed some more light on the topic.

The GPL License Mixing.

Can a GPLv2 program rely on Apache-licensed libraries?


问:
Where does the the term "feature creep" come from?
There is a decent Wikipedia article on the "Feature Creep", but it doesn't state an origin. A Google search only leads to some vague article claiming "Earl Rich" coined the term, but there isn't much backup for that claim. There is a Dilbert comic from 2001 on the subject, but the tone seems to imply that the term pre-existed; more or less confirmed by the fact that Google has results pre-2000. However, finding the exact origin proofs difficult.

So, who, if anyone at all, coined the term "Feature Creep"? Where does it come from?

答:
The etymologic history of computer jargon is well documented in the Jargon file (current version as of this writing is 4.4.8).

The specific term "Feature Creep" is listed as "New in 4.1.0" in the change log.  4.1.0 dates to March 12, 1999 and is defined as:

feature creep: n.  The result of {creeping featurism},    as in "Emacs
  has a bad case of feature creep".

While this is the earliest use of the word in specific context, there are indications that the phrase existed earlier in some form.

The begining of each jargon file has a section on the various non-word aspects of the use of language by computer types.

In an early version of the Jargon file from 1981:

```<code>Soundalike slang: similar to Cockney rhyming slang.  Often made up on
   the spur of the moment.  Standard examples:
    Boston Globe => Boston Glob
    Herald American => Horrid (Harried) American
    New York Times => New York Slime
    historical reasons => hysterical raisins
    government property - do not duplicate (seen on keys)
        => government duplicity - do not propagate
   Often the substitution will be made in such a way as to slip in
   a standard jargon word:
    Dr. Dobb's Journal => Dr. Frob's Journal
    creeping featurism => feeping creaturism
    Margaret Jacks Hall => Marginal Hacks Hall
</code>```

The "creeping featurism" entry suggests that the term may have been used, if not in that exact form of "feature creep".

Thus, language the term existed for certain in 1999 in the hacker (realize that the term "hacker" in the jargon file is a different group than it is today) community.

Indications that the phrase existed, though didn't formally enter the lexicon show up as early as 1981 and may have been common usage in the MIT and Stanford communities.

The concept of "feature creep" can be documented in 1975 as part of the Mythical Man Month.  In one of the essays within this collection, "Second System Effect" is described. From the Wikipedia summary:

The second-system effect proposes that, when an architect designs a
  second system, it is the most dangerous system he will ever design,
  because he will tend to incorporate all of the additions he originated
  but did not add (due to inherent time constraints) to the first
  system. Thus, when embarking upon a second system, an engineer should
  be mindful that he is susceptible to over-engineering it.

Realize the difference between the Mythical Man Month and the Jargon file likely represents two different cultures - the Mythical Man Month is from a project management perspective while the jargon file is more from the hacker/academic perspective.

Body:
The etymologic history of computer jargon is well documented in the Jargon file (current version as of this writing is 4.4.8).

The specific term "Feature Creep" is listed as "New in 4.1.0" in the change log.  4.1.0 dates to March 12, 1999 and is defined as:

feature creep: n.  The result of {creeping featurism},    as in "Emacs
  has a bad case of feature creep".

While this is the earliest use of the word in specific context, there are indications that the phrase existed earlier in some form.

The begining of each jargon file has a section on the various non-word aspects of the use of language by computer types.

In an early version of the Jargon file from 1981:

Soundalike slang: similar to Cockney rhyming slang.  Often made up on
   the spur of the moment.  Standard examples:
    Boston Globe => Boston Glob
    Herald American => Horrid (Harried) American
    New York Times => New York Slime
    historical reasons => hysterical raisins
    government property - do not duplicate (seen on keys)
        => government duplicity - do not propagate
   Often the substitution will be made in such a way as to slip in
   a standard jargon word:
    Dr. Dobb's Journal => Dr. Frob's Journal
    creeping featurism => feeping creaturism
    Margaret Jacks Hall => Marginal Hacks Hall

The "creeping featurism" entry suggests that the term may have been used, if not in that exact form of "feature creep".

Thus, language the term existed for certain in 1999 in the hacker (realize that the term "hacker" in the jargon file is a different group than it is today) community.

Indications that the phrase existed, though didn't formally enter the lexicon show up as early as 1981 and may have been common usage in the MIT and Stanford communities.

The concept of "feature creep" can be documented in 1975 as part of the Mythical Man Month.  In one of the essays within this collection, "Second System Effect" is described. From the Wikipedia summary:

The second-system effect proposes that, when an architect designs a
  second system, it is the most dangerous system he will ever design,
  because he will tend to incorporate all of the additions he originated
  but did not add (due to inherent time constraints) to the first
  system. Thus, when embarking upon a second system, an engineer should
  be mindful that he is susceptible to over-engineering it.

Realize the difference between the Mythical Man Month and the Jargon file likely represents two different cultures - the Mythical Man Month is from a project management perspective while the jargon file is more from the hacker/academic perspective.


问:
How can "hash functions" be used to implement hash maps at all?
My understandment is that hash maps allow us to link, say, a string, to certain memory location. But if every string were to be linked to a unique place in memory it would need a huge block of empty memory. I don't get it.</p>

答:
Hash functions are used to convert the input (usually string) to a smaller fixed length (typically) "hashed value" which typically is used somewhat like a array index for the hash table. Ideally this value should be evenly spread throughout its range, and avoid any obvious/significant concentrations.

A hash function is any algorithm or subroutine that maps large data sets of variable length, called keys, to smaller data sets of a fixed length.

You have been miss informed with regards to the "certain memory location". The use of such a function is to reduce a large piece of data into a much smaller value which can be used to identify that large data. Since you are reducing the size of the data however, it is likely that more than one input "data" will have the same hashed value - that is what is called collision.

A valid hash function (not a very good one, but valid still) could be one that sums up each of  the letters of the string by their ASCII codes.


问:
How would one handle external dependencies in an open-source project?
When one writes an open-source project and uses Google Code or GitHub, and wants to use a library like Lua, how should one do this?

Should the dependency be included in the repository?

Should the dependency be built from within the same build script as the rest of the project, or from a separate build script?

Given that the library doesn't need installation before compilation.

答:
Should the dependency be included in the repository?

It can be referenced in repository (by any usable for SCM method), if this dependency is integral part of product (source-dependence), not binary-dependence, which can be resolved separately

Should the dependency be built from within the same build script as the rest of the project, or from a separate build script?

Doesn't matter at all. You can prefer any method, according to your requirements (speed/transparency/manageability/etc)


答:
Feature creep

The phrase feature creep dates to at least 1990, as used in a comp.sys.mac Usenet post on the San Francisco MacWorld Expo of April 15, 1990:

As an industry 'matures' everyone starts to look
  the same and the shows
  get less interesting, fewer and fewer really
  wonderfully new and
  striking products (I think it's because all the
  relatively obvious stuff gets done). Everyone ends up playing 'feature creep' with their competitors.

Three months later in the same group, a reply to a "Finder 7.0 suggestion" on July 13, 1990:

There's really no need for something that specific:
  System 7.0's
  InterApplication Communication model already
  provides a foundation for
  doing this sort of thing. ...   Apple hasn't actually
  designed a stream Manager with the functions that you describe,
  probably because they
  wanted to leave something for the developers to
  do. I also suspect
  that Apple System Software Engineers probably
  have better things to worry about than standardizing a Spelling
  dictionary. In a previous
  message, somebody mentioned Feature Creep, and I think it applies very
  well.

By 1993, it was more common in Usenet.

Creeping featurism

The earlier phrase creeping featurism shows up in Jargon File 1.1.3 (dated 22nd July 1981) as a form of soundalike slang:

creeping featurism => feeping creaturism

Feature creep itself doesn't show up until Jargon File 4.1.0 (dated 12th March 1999):

:feature creep: n.  The result of {creeping featurism},    as in
  "Emacs has a bad case of feature creep".

Requirements creep

The synonymous feature creep shows up in snippets of the Department of Defense Authorization for Appropriations for Fiscal Year 1985, published in 1984:

Experience has shown that longer production runs result in requirements "creep". To improve this estimate for budgetary purposes would require the Air Force to formally task the contractors to provide cost estimates detail keyed to a hypothetical production rate.

The following year, a snippet of Department of Defense appropriations for 1986: hearings before a subcommittee of the Committee on Appropriations, House of Representatives, Ninety-ninth Congress, first session, Part 2 says:

We have put a very solid reign on gold-plating, on requirements creep, and on engineering change orders. Everything that has any impact on the cost of a contract once signed, must be approved for a waiver by the CNO, by me or the Commandant if it is a Marine program.

In 1986 it shows up in IEEE documents about avionics, and in 1987 IEEE conference records, and from there into other software engineering books.

Mission creep

Feature creep probably isn't derived from mission creep, defined by the Oxford English Dictionary as:

orig. U.S. Mil. slang a gradual
  shift in political or strategic objectives during the
  course of a military campaign, frequently
  resulting in an unresolved conflict or open-ended
  commitment; also in extended use.

Their first citation is from 1991:

We're going into a conflict with an ill-defined
  mission, there is mission creep in a much more
  compressed time frame, [etc.].

The earliest I found is in the Los Angeles Times of Sunday, June 27, 1993 ("Soldiers of the New World Order - Aggressive Peacemakers, U.S. Marines Draw Down the Warlords of Somalia and Write a Military Blueprint for Future Campaigns"):

But Abbot never did just the minimum in Somalia; he was singled out, in fact, by Gen. Johnston as one of the commanders who went beyond the Marines' primary mission of securing food-supply routes and neutralizing Somalia's warring clans and bandits--a task accomplished within two months of the Marines' arrival--into such development projects as rebuilding local police departments, schools and community centers. Johnston called it "Mission Creep."

Other creep

Here's a 1960 "nucleur creep" and a 1983 "speciality creep", both from Military Review.

Title: Where does the the term "feature creep" come from?

Body:
There is a decent Wikipedia article on the "Feature Creep", but it doesn't state an origin. A Google search only leads to some vague article claiming "Earl Rich" coined the term, but there isn't much backup for that claim. There is a Dilbert comic from 2001 on the subject, but the tone seems to imply that the term pre-existed; more or less confirmed by the fact that Google has results pre-2000. However, finding the exact origin proofs difficult.

So, who, if anyone at all, coined the term "Feature Creep"? Where does it come from?


答:
Hash and map are two different concepts. (And hence two tags hashing and map :-)).

The concept of map (in this context) is collection of key-value pairs, where key could be anything and value could be anything. Once you created a map, map should be able to retrieve value of a given key. A simple map could be storing the key-value pair in an array, or linked list. A map can be implemented using any storage technique. Popular are Red-Black Trees and Hashing.

Hashing is converting anything into a unique representation (most of the times as random as possible) which is limited by some range. Hashing is one way, means once you hash A into B there is no guaranteed way to get A from B.

A hash function is one which takes A as input and returns B as output. Two properties for hash functions are important.

It should always return same B given the same A.

Ideally it should return different B for different A. But it is impossible if the range of B is smaller than range of A.

Getting a good hash function is really difficult as maintaining property 2 is quite difficult. A simplest hash function is modulo operator. There exists a good lot of hash algorithms and libraries.

Now what you get when you combine these two? A hash map. The key is converted to hash and stored against the value. So if I have a pair (A,A'), I will convert A to hash B and store (B, A'). Now If I want to get what is the value stored against key A, I will first convert A to B and then see what is stored against B, and return it.

The advantage of using hash map is the fast retrieval. It is O(1), i.e. in constant time I can find whether a key is present and the value against it. Compare it to Red-Black Tree where the time complexity of retrieving is O(logn). (There is also time of inserting and deleting which I am not discussing here.)

So now tell me what's your question?

Title: How can "hash functions" be used to implement hash maps at all?

Body: My understandment is that hash maps allow us to link, say, a string, to certain memory location. But if every string were to be linked to a unique place in memory it would need a huge block of empty memory. I don't get it.</p>


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答: The Last Lecture a book written by Randy Pausch the man behind Alice. It goes along with his last lecture "Really Achieving your Childhood Dreams". Always gotta remember to be a Tigger.</p>


问:
Parsing a Log File - Java
Im reading a log file in Java on a Linux box on a continual schedule of 2 minutes looking for certain messages. I store the last offset (RandomAccessFile getFilePointer) and read from it onwards when I detect LastModified has changed; is this best practice or even right?</p>

答:
If it works, then it's good enough. The only problems I see with this solution is two-fold:

What happens if someone edits the log file? The java program will ignore these changes.

What happens if the logger splits up the log file? The last offset file pointer will be invalid.

The first point is a bit of a stretch since it is a bad idea to edit a log file (as users are only supposed to append to the file). Second point is a common practice, that the log file is split in dates or at some amount of lines.

Title: Parsing a Log File - Java


答:
Assuming the following:

this log file is only appended to

you're prepared to meet the possibility that the file no longer exists / shorter than your current offset

program writing to log wouldn't attempt to delete the log file (since you may be reading it at the time) or that it handles such situations well

You shouldn't have much to worry about.  Just remember to close the file after reading it and to open it with "r" mode only.

Title: Parsing a Log File - Java

Body: Im reading a log file in Java on a Linux box on a continual schedule of 2 minutes looking for certain messages. I store the last offset (RandomAccessFile getFilePointer) and read from it onwards when I detect LastModified has changed; is this best practice or even right?</p>


问:
Emphasize negation
I was just writing an if statement with fairly long property names and came occross this problem.

Let say we have an if statement like this:

```<code>if(_someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue &&
   !_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant)
{
    //Do something
}
</code>```

The second property is of a boolean type and it makes no sense to have the stetement like

```<code>if(boleanValue == true)
</code>```

Is there a better way to emphasize the negation then to put the ! in front. To me it seems like this can easily be overseen when reading the code and may potentialy cause problems with debuging

答:
Put it in its own if block prior to evaluating the less important conditions. Not only would it be easier to read without the clutter of the other conditions, but it's also the first condition a programmer will read. Combine this with the idea already mentioned by @scrwtp to assign to a variable with a meaningful name and you get:

```<code>var isValid = !_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant;
if( isValid )
{
    if( _someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue )
    {
        //Do something
    }
}
</code>```

If you're programming in a compiler language, most times these nested if blocks get combined in the end anyway, so long as you don't insert code between the outer if and the inner if, so it shouldn't affect performance in these cases.

Title: Emphasize negation

Body:
Put it in its own if block prior to evaluating the less important conditions. Not only would it be easier to read without the clutter of the other conditions, but it's also the first condition a programmer will read. Combine this with the idea already mentioned by @scrwtp to assign to a variable with a meaningful name and you get:

var isValid = !_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant;
if( isValid )
{
    if( _someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue )
    {
        //Do something
    }
}

If you're programming in a compiler language, most times these nested if blocks get combined in the end anyway, so long as you don't insert code between the outer if and the inner if, so it shouldn't affect performance in these cases.


答:
```<code>if(_someViewModelNameThatIsLong.NeedsMeToDoSomething(someValue))
{
    //Do something
}
</code>```

And then, in the view model object

```<code>public bool NeedsMeToDoSomething(string someValue)
{
    return AnotherPropertyINeedToCheck == someValue &&
        !ThisIsABooleanPropertyThatIsImportant;
}
</code>```

(assuming someValue is a string and isn't known by the model object)

This not only emphasises the ! operator, but it makes it more readable generally. Now, in the calling method, I can see one condition, which should be well-named to describe the condition in the context of the calling object. And in the model object, I can see what that means in the context of the model object.

Title: Emphasize negation

Body:
I was just writing an if statement with fairly long property names and came occross this problem.

Let say we have an if statement like this:

```<code>if(_someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue &&
   !_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant)
{
    //Do something
}
</code>```

The second property is of a boolean type and it makes no sense to have the stetement like

```<code>if(boleanValue == true)
</code>```

Is there a better way to emphasize the negation then to put the ! in front. To me it seems like this can easily be overseen when reading the code and may potentialy cause problems with debuging

Body:
if(_someViewModelNameThatIsLong.NeedsMeToDoSomething(someValue))
{
    //Do something
}

And then, in the view model object

public bool NeedsMeToDoSomething(string someValue)
{
    return AnotherPropertyINeedToCheck == someValue &&
        !ThisIsABooleanPropertyThatIsImportant;
}

(assuming someValue is a string and isn't known by the model object)

This not only emphasises the ! operator, but it makes it more readable generally. Now, in the calling method, I can see one condition, which should be well-named to describe the condition in the context of the calling object. And in the model object, I can see what that means in the context of the model object.


问:
Where did the T in wchar_t come from?
In many native types, a common suffix (and sometimes prefix) of t or _t is used to denote platform-independent types (such as wchar_t, int32_t, etc.)

What was the logic behind the letter t as opposed to other letters (or none at all, especially in the case of wchar_t)? Does it stand for something?

答: As opposed to _s which commonly denotes C structs I always envisioned _t to stand for typedefs.</p>

Title: Where did the T in wchar_t come from?


问:
What are the common mistakes when you are a good coder in C and PHP and you start coding in Java ? What are good tips when switching?
What apsects of Java are the most diificult to learn when coming from such a background?  What common mistakes do people make ? What are the top timesaving and produtivtity increasing tricks ?

If you had a room of C/PHP coders who were about to start development using Java what advise would you give ?

This is my list of topics so far (in no particular order):

Use jodatime instead of the standard
library , and also less importantly
the guava library.

Arrays are zero indexed

I'd also highlight the
pass-by-value/reference aspects of
Java, and the fact that

```<code>String s1 = new String("test");
String s2 = new String("test");
if(s1 == s2) // will be false
if(s1.equals(s2)) // will be true
</code>```

Introduce the concept of design
patterns and give a quick overview.

Introduce Spring (it will be used) and the concept of
dependency injection

Is there anything obvious I am missing.

答:
Few points that PHP developer needs to know to code in Java:

Different type of collections are available in Java, in PHP only arrays is most commonly used so many PHP developers won't be aware of collections concepts.

Packaging : packaging is not generally used in PHP so they need to understand concepts like jar, war etc

Threads & Thread safety : if PHP is the only language they know threads is going to be entirely new concept.

Different application servers in Java, in PHP world it's just Apache.

Design patterns: Java world much emphasis is given for design patterns than in php.


答:
I'd just extract

```<code>`!_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant`
</code>```

In a Method that returns this. If you name this method NotThisIsABooleanPropertyThatIsImportant
you should be fine.

Title: Emphasize negation

Body:
I'd just extract

`!_someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant`

In a Method that returns this. If you name this method NotThisIsABooleanPropertyThatIsImportant
you should be fine.


答:
For two of your remarks :

I'd also highlight the pass-by-value/reference aspects of Java, and
  the fact that ...

One of the best books to deeply understand coding problems is  :"Extreme Java" by Joshua Bloch so:

```<code>String s1 = new String("test"); // bad coding

String s1 = "test"; // sufficient
</code>```

Many and many other samples inside.

If you are obliged to code tomorrow, read inside concerned paragraph before coding, and take a pause to understand that Java is another mind world, even if it C children.

First time it seems very difficult, but soon it is more clear, and powerful.

Introduce the concept of design patterns and give a quick overview.

THE book designed for beginners to understand Java and OOP problems : Head First Design Patterns.

Tips/sample

Have a look at Collections or Pattern in Java package classes to understand good writing,

Title: What are the common mistakes when you are a good coder in C and PHP and you start coding in Java ? What are good tips when switching?

Body:
What apsects of Java are the most diificult to learn when coming from such a background?  What common mistakes do people make ? What are the top timesaving and produtivtity increasing tricks ?

If you had a room of C/PHP coders who were about to start development using Java what advise would you give ?

This is my list of topics so far (in no particular order):

Use jodatime instead of the standard
library , and also less importantly
the guava library.

Arrays are zero indexed

I'd also highlight the
pass-by-value/reference aspects of
Java, and the fact that

```<code>String s1 = new String("test");
String s2 = new String("test");
if(s1 == s2) // will be false
if(s1.equals(s2)) // will be true
</code>```

Introduce the concept of design
patterns and give a quick overview.

Introduce Spring (it will be used) and the concept of
dependency injection

Is there anything obvious I am missing.

Body:
For two of your remarks :

I'd also highlight the pass-by-value/reference aspects of Java, and
  the fact that ...

One of the best books to deeply understand coding problems is  :"Extreme Java" by Joshua Bloch so:

String s1 = new String("test"); // bad coding

String s1 = "test"; // sufficient

Many and many other samples inside.

If you are obliged to code tomorrow, read inside concerned paragraph before coding, and take a pause to understand that Java is another mind world, even if it C children.

First time it seems very difficult, but soon it is more clear, and powerful.

Introduce the concept of design patterns and give a quick overview.

THE book designed for beginners to understand Java and OOP problems : Head First Design Patterns.

Tips/sample

Have a look at Collections or Pattern in Java package classes to understand good writing,


问:
First Class Functions
I started seriously taking a look at Lisp this weekend (by which I mean I have only been learning Lisp and not reverting back to projects in C#) and must say I love it. I have dabbled with other functional languages (F#, Haskell, Erlang) but haven't felt the draw that Lisp has given me.

Now as I continue to learn Lisp, I have started wondering why non-functional languages don't support first-class functions. I know that languages such as C# can do similar things with delegates and to an extent you can use pointers to functions in C/C++ but is there a reason why this would never become a feature in those languages? Is there a drawback to making functions first-class? To me, it is extremely useful, so I am lost as to why more languages (outside the functional paradigm) don't implement it.

[Edit]I appreciate the responses so far. Since I have been shown that many languages now support first-class functions now, I'll re-phrase the question to be why would it take so long for languages to implement them? [/Edit]

答:
First-class functions are a lot less interesting without closures.

Closures aren't really possible without some kind of dynamic management of scope (garbage collection). One of the things that makes C/C++ so highly performant is the fact that it's a lot easier to compile a language where you manage memory manually, so that kinda takes C/C++ out of the equation.

And then yes, there is the matter of OOP impact. You no longer have a separation of methods and properties. Methods are themselves properties that accept functions as values. In that context, what does it really mean to overload methods since you can just swap the silly things out at any time. Can you really add that to Java, for instance, without introducing a major paradigm shift to the entire language? Where's the contract or that sense of (IMO false) security people get from knowing the construct guarantees it will always work the same way every time? It might make sense to treat functions tied to objects as methods as a different organism in languages that allowed functions to exist independently in the first place but in Java that's not really an option.

In JavaScript, OOP and functional are very much intertwined and I would personally find it hard to see first-class funcs as anything but bolted-on in languages where they weren't. But that requires a number of other paradigm-shifting changes including high levels of mutability in objects and their methods themselves as well as being able to call functions as if they were members of any object on the fly.

Languages aren't just tool-sets full of do-hickeys for getting things done for the most part. They're paradigms. Bundles of ideas, strategies, and opinions that all kind of go together in a way that's connected (or seem connected). In a lot of cases functions as noun and verb really just don't fit the paradigm at all or at best are an imperfect fit.

That said, I feel like I'm missing an arm when forced to code without them.

Title: First Class Functions


问:
Parallel computing using xcode
I'm making mandelbrot fractals in C using Xcode and I want to use parallel computing but everything I've tried so far doesn't work. Such as This Question and other how to guides. Whats the easiest way to use frameworks such as mpi.h to run my program in parallel?</p>

答:
According to the answers on this StackOverflow question, the compiler included with Xcode 4.5 does not (yet) understand the OpenMP pragmas for parallel execution.

There are other ways to achieve what you want, though. Apple has sample code for a fractal generator written in OpenCL, or you could use Grand Central Dispatch. In any case your main problem is working out which parts of the application can run in parallel and how to synchronise with those that can't.

Title: Parallel computing using xcode


答:
Not using proper Object-Oriented design but procedural. A classical example is switch or many if/else versus polymorphism:</p>

```<code>//procedural way of computing the salary of an employee
if(employeeType == JUNIOR) {
    salary = //junior salary calculation logc;
} else if(employeeType == MID_LEVEL)
    salary = //mid_level salary calculation logc;
} else if(employeeType == SENIOR) {
    salary = //senior salary calculation logc;
}

//OOP way
Employee employee = EmployeeFactory.getEmployee(JUNIOR);
salary = employee.calculateSalary();
//where employee is an interface having calculateSalary method;
//also there are classes for JuniorEmployee, MidLevelEmployee and SeniorEmployee
</code>```

Body:
Not using proper Object-Oriented design but procedural. A classical example is switch or many if/else versus polymorphism:

//procedural way of computing the salary of an employee
if(employeeType == JUNIOR) {
    salary = //junior salary calculation logc;
} else if(employeeType == MID_LEVEL)
    salary = //mid_level salary calculation logc;
} else if(employeeType == SENIOR) {
    salary = //senior salary calculation logc;
}

//OOP way
Employee employee = EmployeeFactory.getEmployee(JUNIOR);
salary = employee.calculateSalary();
//where employee is an interface having calculateSalary method;
//also there are classes for JuniorEmployee, MidLevelEmployee and SeniorEmployee


问:
Javascript simple code to understand prototype-based OOP basics
I know Javascript for some time, although I am not a heavy user, I know it the first from the time when Netscape was my browser. I pretty much understand the main things, but since JavaScript approach to OOP is prototypical I have some problem grasping it.

One problem to add to this it seems that things can be done in more than one way, and here is where books don't help much because they put all the examples on the table making it hard to keep the pace.

What I need for start is only one way of doing it, if someone can help me with the simplest code possible an example where I can see how the prototypal OOP model works?

To be helpful the code should have an inherited object, to access a parent's property and its inherited properties and a parent's function, to overwrite a parent's function and and have an instance of a multiple inheritance where an object inherits two other objects.

答:
Forget code. The simplest explanation.

Function constructors build objects. In JS, functions are themselves objects which can have properties. Every function has a prototype property which can contain any object. You can set any constructors prototype easily on the fly. If you want to ruin arrays for instance,

```<code>Array.prototype = {
    oneTrueMethodToRuleThemAll: function(){
        alert('arrays are now hosed');
    }
}
</code>```

The prototype object is basically a fallback that gets checked by instances when you try to reference a property they don't have. If the prototype  object doesn't have that method, its constructor's prototype object gets checked for the method. That's the chain that gets followed.

So it's not really about inheritance. It's about, "Oh, you don't have that, well does your mother have it in her prototype bag? No? How about her grandmother? No? Then how about .. until we get to Eve, or the Object constructor's prototype which is where the buck always stops.

So it's not that your instances pick up or retain the stuff in the prototype. It's just that when JavaScript calls a method of an object there is fallback process for checking the object->constructor.prototype chain to see if the unknown method can be found. And that's why when you change a constructor prototype, all existing instances "get" that method. They don't really get anything at all. It's their fallback set of objects for lookup that gets the new method.

Body:
Forget code. The simplest explanation.

Function constructors build objects. In JS, functions are themselves objects which can have properties. Every function has a prototype property which can contain any object. You can set any constructors prototype easily on the fly. If you want to ruin arrays for instance,

Array.prototype = {
    oneTrueMethodToRuleThemAll: function(){
        alert('arrays are now hosed');
    }
}

The prototype object is basically a fallback that gets checked by instances when you try to reference a property they don't have. If the prototype  object doesn't have that method, its constructor's prototype object gets checked for the method. That's the chain that gets followed.

So it's not really about inheritance. It's about, "Oh, you don't have that, well does your mother have it in her prototype bag? No? How about her grandmother? No? Then how about .. until we get to Eve, or the Object constructor's prototype which is where the buck always stops.

So it's not that your instances pick up or retain the stuff in the prototype. It's just that when JavaScript calls a method of an object there is fallback process for checking the object->constructor.prototype chain to see if the unknown method can be found. And that's why when you change a constructor prototype, all existing instances "get" that method. They don't really get anything at all. It's their fallback set of objects for lookup that gets the new method.


答:
From http://www.apache.org/licenses/GPL-compatibility.html

Apache 2 software can therefore be included in GPLv3 projects, because
  the GPLv3 license accepts our software into GPLv3 works. However,
  GPLv3 software cannot be included in Apache projects. The licenses are
  incompatible in one direction only, and it is a result of ASF's
  licensing philosophy and the GPLv3 authors' interpretation of
  copyright law.

So you can use! if you release your software to GPL v3.

Title: Software has sub-part Apache v2 license and other sub-part GPL v2 license

Body:
Firstly I am sorry I do not fully understand about licensing. Thus I want to ask here for my curiosity about licensing things.

Here is the case. I build a WordPress theme that using underscores.me as its starter theme. It has GPL v2 license. And then I build the theme using Twitter Bootstrap. It has Apache v2 license.

I have been searching about both licenses. I found that Apache v2 is only compatible with GPL v3, not GPL v2.

What license can put to my code? Apache? GPl? Or I just can not release it because of Apache v2 and GPL 2 are incompatible? Finally, does it matter whether or not I modify the code?


问:
Shorter release cycle with DVCS
Does the choice of using a DVCS over a CVCS actually make for shorter release cycles?  If so, what makes software release cycles shorter and what are the arguments for this?

Related to pull request? Does easier submission of patches play a role here?

Related to people factor? Are project teams that use CVCS act more conservative with release schedules?

Any other factors?

答:
Everyone here seems to agree that projects using DVCS have shorter release cycles over all, but it's still not certain that the adoption of a DVCS causes the shorter cycles: Correlation is not causation!

Distributed VCS and short release cycles are both relatively new technologies. Projects that embrace one are likely to embrace the other, while groups that prefer the tried and true, or that have a long-established workflow, will be more conservative and stick with CVCS and less frequent releases.

A better question to ask would be: "In what ways does use of a DVCS facilitate the short release cycle model?" This is what most of the answers are addressing, as a matter of fact. Using a DVCS doesn't prevent anyone from having long release cycles; adopting short ones is a choice, and it involves development methodologies, branching models, code reviews, etc.-- not just the VCS.

Title: Shorter release cycle with DVCS


问:
Detecting IEnumerable "State Machines"
I just read an interesting article called Getting too cute with c# yield return

It made me wonder what the best way is to detect whether an IEnumerable is an actual enumerable collection, or if it's a state machine generated with the yield keyword.

For example, you could modify DoubleXValue (from the article) to something like:

```<code>private void DoubleXValue(IEnumerable<Point> points)
{
    if(points is List<Point>)
      foreach (var point in points)
        point.X *= 2;
    else throw YouCantDoThatException();
}
</code>```

Question 1) Is there a better way to do this?

Question 2) Is this something I should worry about when creating an API?

答:
I personally think the problem highlighted in that article stems from overuse of the IEnumerable interface by many C# developers these days. It seems to have become the default type when you're requiring a collection of objects - but there's a lot of information that IEnumerable simply doesn't tell you... crucially: whether or not it has been reified*.

If you find that you need to detect whether an IEnumerable is truly an IEnumerable or something else, the abstraction has leaked and you're probably in a situation where your parameter type is a little too loose. If you require the extra information that IEnumerable alone doesn't provide, make that requirement explicit by choosing one of the other interfaces such as ICollection or IList.

Edit for the downvoters
Please go back and read the question carefully. The OP is asking for a way to ensure that IEnumerable instances have been materialized before being passed to his API method. My answer addresses that question. There is a wider issue regarding the proper way to use IEnumerable, and certainly the expectations of the code the OP pasted are based on a misunderstanding of that wider issue, but the OP did not ask how to correctly use IEnumerable, or how to work with immutable types. It's not fair to downvote me for not answering a question which was not posed.

* I use the term reify, others use stabilize or materialize. I don't think a common convention has been adopted by the community just yet.

Title: Detecting IEnumerable "State Machines"


问:
How do you balance between "do it right" and "do it ASAP" in your daily work?
I find myself pondering over this question from time to time, again and again. I want to do things the right way: to write clean, understandable and correct code that is easy to maintain. However, what I end up doing is writing patch upon a patch; just because there is no time, clients are waiting, a bug should be fixed overnight, the company is losing money on this problem, a manager is pressing hard etc., etc.

I know perfectly well that in the long term I am wasting more time on these patches, but as this time spans months of work, nobody cares. Also, as one of my managers used to say: "we don't know if there will be a long term if we don't fix it now."

I am sure I am not the only one entrapped in these endless real/ideal choice cycles. So how do you, my fellow programmers, cope with this?

UPDATE:
Thank you all for this interesting discussion.
It is sad that so many people have to choose daily between a quantity and a quality of their code. Still, surprisingly many, people think it is possible to win this battle, so thank you all for this encouragement.

答:
If it's a bug, do it ASAP, if it's a new feature, take your time.

And if you work for a company that does not respect developer work, you may have not choice but to do it fast and sacrifice on quality.

I've worked for a number of companies that would just go from project to project, and do everything fast. Ultimately, they had little success in every project because the implementation (not just the programming) was rushed through.

The best companies out there understand that good software takes time and craftsmanship.


问:
Temporary variables vs line length requirements
I've been reading Martin Fowler's Refactoring. It is generally excellent but one of Fowler's recommendations seems to be causing a little trouble.

Fowler recommends that you replace temporary variables with a query, so instead of this:

```<code>double getPrice() {
    final int basePrice = _quantity * _itemPrice;
    final double discountFactor;
    if (basePrice > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice * discountFactor;
}
</code>```

you pull out into a helper method:

```<code>double basePrice() {
    return _quantity * _itemPrice;
}

double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice() * discountFactor;
}
</code>```

In general I agree except that one reason I use temporary variables is when a line is too long. For example:

```<code>$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);
</code>```

If I tried inlining that, the line would go longer than 80 characters.

Alternately I end up with chains of code, which are themselves not that much easier to read:

```<code>$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));
</code>```

What are some strategies for reconciling the two?

答:
If you happen to work in a language with named parameters (ObjectiveC, Python, Ruby, etc), temp vars are less useful.

However, in your basePrice example, the query may take a while to execute and you may want to store the result in a temp variable for future use.

Like you, though, I use temp variables for clarity and line length considerations.

I've also seen programmers do the following in PHP. It's interesting and great for debugging, but it's a little strange.

```<code>$rs = DB::query( $query = "SELECT * FROM table" );
if (DEBUG) echo $query;
// do something with $rs
</code>```

Body:
If you happen to work in a language with named parameters (ObjectiveC, Python, Ruby, etc), temp vars are less useful.

However, in your basePrice example, the query may take a while to execute and you may want to store the result in a temp variable for future use.

Like you, though, I use temp variables for clarity and line length considerations.

I've also seen programmers do the following in PHP. It's interesting and great for debugging, but it's a little strange.

$rs = DB::query( $query = "SELECT * FROM table" );
if (DEBUG) echo $query;
// do something with $rs


答:
I think the key concept is that you should treat any IEnumerable<T> collection as immutable: you shouldn't modify the objects from it, you should create a new collection with new objects:

```<code>private IEnumerable<Point> DoubleXValue(IEnumerable<Point> points)
{
    foreach (var point in points)
        yield return new Point(point.X * 2, point.Y);
}
</code>```

(Or write the same more succinctly using LINQ Select().)

If you actually want to modify the items in the collection, don't use IEnumerable<T>, use IList<T> (or possibly IReadOnlyList<T> if you don't want to modify the collection itself, only items in it, and you're on .Net 4.5):

```<code>private void DoubleXValue(IList<Point> points)
{
    foreach (var point in points)
        point.X *= 2;
}
</code>```

This way, if someone attempts to use your method with IEnumerable<T>, it will fail at compile time.

Title: Detecting IEnumerable "State Machines"

Body:
I just read an interesting article called Getting too cute with c# yield return

It made me wonder what the best way is to detect whether an IEnumerable is an actual enumerable collection, or if it's a state machine generated with the yield keyword.

For example, you could modify DoubleXValue (from the article) to something like:

```<code>private void DoubleXValue(IEnumerable<Point> points)
{
    if(points is List<Point>)
      foreach (var point in points)
        point.X *= 2;
    else throw YouCantDoThatException();
}
</code>```

Question 1) Is there a better way to do this?

Question 2) Is this something I should worry about when creating an API?

Body:
I think the key concept is that you should treat any IEnumerable<T> collection as immutable: you shouldn't modify the objects from it, you should create a new collection with new objects:

private IEnumerable<Point> DoubleXValue(IEnumerable<Point> points)
{
    foreach (var point in points)
        yield return new Point(point.X * 2, point.Y);
}

(Or write the same more succinctly using LINQ Select().)

If you actually want to modify the items in the collection, don't use IEnumerable<T>, use IList<T> (or possibly IReadOnlyList<T> if you don't want to modify the collection itself, only items in it, and you're on .Net 4.5):

private void DoubleXValue(IList<Point> points)
{
    foreach (var point in points)
        point.X *= 2;
}

This way, if someone attempts to use your method with IEnumerable<T>, it will fail at compile time.


问:
Java memory management (thunks/lazyness)
If I want to create an infinite list of integers in Java like so:

```<code>ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0;;i++){
    list.add(i);
}
</code>```

I run out of memory. My understanding is that we allocate some memory for i, list, and every time we add i to the list, we allocate more memory for it.

But, by using a thunk, I can create an infinite list which will not eat all of my memory:

```<code>infList(final int start){
    return new InfiniteList (
    start,
    return new InfiniteList.LazyTail(){eval(){return infList(start+1);}}
    );
}
</code>```

(I adapted source from here). How does this work? I know I am delaying the evaluation of the expressions : start+1, start+1, start+1 ... but do I end up with a list of something like this:

[start, eval(){start+1}, eval(){start+1}, eval(){start+1} ... ]

Are the 'eval(){...}' object references? Do they take up space in memory? Will I eventually run out of memory with this implementation (I tried, but memory allocation was not budging)?

Do I only start using memory, say, if I wanted to system.out.print integers, then they would have to be evaluated, and some memory allocated?

答:
No matter how you cut the cake, an integer takes up space in memory (32-bits in Java to be exact) and an infinite number of them will take up an infinite amount of space. This will cause you to run out of memory(1). Any solution that claims to create an infinite list is not actually creating a list, just an illusion. For example, your loop would make System.out.println(list.get(10000); print out 10000. I could very easily devise a simple object with a method called get(int x) that just returns x. This would create the illusion of an infinite list of integers.

Side Note (1): Depending on how much memory you can allocate to the list, you may hit the maximum integer size of ~2 billion before running out of memory. This would require something in the ballpark of 15 GB of memory to hit this limit.


答:
This is classic lazy initialisation as in the objects that are never referenced are never created; only when they are first referenced does the initialization occur.

FYI to create a infinite list in java you can do the following:

```<code>public class InfList extends AbstractList<Integer> implements RandomAccess{

    public Integer get(int i){
        return i;
    }

    public int size(){
        return Integer.MAX_value;
    }

}
</code>```

or to use a more traditional predicate based list:

```<code>public class FibList extends AbstractSequentialList<BigInteger> {

    public ListIterator<BigInteger> listIterator(int i){
         ListIterator<BigInteger> res = new FibIterator(0,1);
         for(;i>0;i++)res.next();
         return res;
    }

    private FibIterator implements ListIterator<BigInteger>{
        BigInteger prev,curr;int ind=0;

        FibIterator(int pr,int c){
            prev=BigInteger.valueOf(pr);
            curr=BigInteger.valueOf(c);
        }

        public boolean hasNext(){return true;}
        public boolean hasPrevious(){return true;}
        public void remove(){throw new UnsupportedOperationException();}
        public void set(BigInterger I){throw new UnsupportedOperationException();}
        public void add(BigInterger I){throw new UnsupportedOperationException();}
        public BigInteger next(){
            BigInteger tmp = curr;
            curr=curr.add(prev);
            prev=tmp;
            ind++;
            return tmp;
        }
        public BigInteger previous(){
            BigInteger tmp = prev;
            prev=curr.subtract(prev);
            curr=tmp;
            ind--;
            return tmp;
        }
        public int nextIndex(){return ind;}
        public int previousIndex(){return ind-;}
    }
}
</code>```

(yeah iterator based list are a pain)

Title: Java memory management (thunks/lazyness)

Body:
If I want to create an infinite list of integers in Java like so:

```<code>ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0;;i++){
    list.add(i);
}
</code>```

I run out of memory. My understanding is that we allocate some memory for i, list, and every time we add i to the list, we allocate more memory for it.

But, by using a thunk, I can create an infinite list which will not eat all of my memory:

```<code>infList(final int start){
    return new InfiniteList (
    start,
    return new InfiniteList.LazyTail(){eval(){return infList(start+1);}}
    );
}
</code>```

(I adapted source from here). How does this work? I know I am delaying the evaluation of the expressions : start+1, start+1, start+1 ... but do I end up with a list of something like this:

[start, eval(){start+1}, eval(){start+1}, eval(){start+1} ... ]

Are the 'eval(){...}' object references? Do they take up space in memory? Will I eventually run out of memory with this implementation (I tried, but memory allocation was not budging)?

Do I only start using memory, say, if I wanted to system.out.print integers, then they would have to be evaluated, and some memory allocated?

Body:
This is classic lazy initialisation as in the objects that are never referenced are never created; only when they are first referenced does the initialization occur.

FYI to create a infinite list in java you can do the following:

public class InfList extends AbstractList<Integer> implements RandomAccess{

    public Integer get(int i){
        return i;
    }

    public int size(){
        return Integer.MAX_value;
    }

}

or to use a more traditional predicate based list:

public class FibList extends AbstractSequentialList<BigInteger> {

    public ListIterator<BigInteger> listIterator(int i){
         ListIterator<BigInteger> res = new FibIterator(0,1);
         for(;i>0;i++)res.next();
         return res;
    }

    private FibIterator implements ListIterator<BigInteger>{
        BigInteger prev,curr;int ind=0;

        FibIterator(int pr,int c){
            prev=BigInteger.valueOf(pr);
            curr=BigInteger.valueOf(c);
        }

        public boolean hasNext(){return true;}
        public boolean hasPrevious(){return true;}
        public void remove(){throw new UnsupportedOperationException();}
        public void set(BigInterger I){throw new UnsupportedOperationException();}
        public void add(BigInterger I){throw new UnsupportedOperationException();}
        public BigInteger next(){
            BigInteger tmp = curr;
            curr=curr.add(prev);
            prev=tmp;
            ind++;
            return tmp;
        }
        public BigInteger previous(){
            BigInteger tmp = prev;
            prev=curr.subtract(prev);
            curr=tmp;
            ind--;
            return tmp;
        }
        public int nextIndex(){return ind;}
        public int previousIndex(){return ind-;}
    }
}

(yeah iterator based list are a pain)


问:
Can I apply SOLID concepts to entire solution designs rather than just the internal components?
So maybe the quick answer is 'Yes' absolutely (or no I suppose), but let me explain my question angle to get a better derived answer.

We all commonly use SOLID design principals when making up the pieces and parts of our applications. Don't make a class do too many things, don't make an Interface too large, use abstraction not concretions, etc.

Is it OK to apply this mentality at an abstract level when thinking about solutions, services, etc.? The main problem: I'm struggling with the request to have a single service do all things related to a specific business domain. Add to this multiple teams would all have their hands in the pot of the same application to add whatever functionality needed.

I have a service being built out with many good architecture and design principals in mind and  believe totally that lots of 'additional' functionality could be bolted on vertically within the same framework and solution. After all this one of the reasons why we spend time architecting solutions to be loosely coupled and allow scalability with rather ease. So you might say, "go for it, if the framework can handle it then add away!"

Something is not sitting right with me and I would be concerned with a behemoth of an application/service that tries to do everything. I tried doing searches about "applications that do too much" or "services that have too many responsibilities" but not much came up. When I start thinking about the SOLID principals, I think having a service that does everything related to a specific business domain might not be a good idea and may cause issues on down the road with maintainability and stepping on each other's toes.

Is it correct to use SOLID principals when looking at entire solution functionality? Is creating a service like http://www.mycompany.com/api/[everyMethodPossible] correct, or could I be doing something that is incorrect?

Thanks!

答:
Is it correct? No.

Correctness has nothing to do with it. The SOLID principles are good, and can be applied outside of OO, like in software architecture or writing functions. Personally, I find them to be useful in doing architecture scoped design, but remember that the goal is to make good software, not to provide the right answers to a test.


答:
Your question, as I understand it, seems to be based on an incorrect premise. Let me see if I can reconstruct the reasoning:

The linked-to article describes how automatically-generated sequences exhibit a "lazy" behaviour, and shows how this can lead to a counter-intuitive result.

Therefore I can detect whether a given instance of IEnumerable is going to exhibit this lazy behaviour by checking to see if it is automatically generated.

How do I do that?

The problem is that the second premise is false. Even if you could detect whether or not a given IEnumerable was the result of an iterator block transformation (and yes, there are ways to do that) it wouldn't help because the assumption is wrong. Let's illustrate why.

```<code>class M { public int P { get; set; } }
class C
{
  public static IEnumerable<M> S1()
  {
    for (int i = 0; i < 3; ++i)
      yield return new M { P = i };
  }

  private static M[] ems = new M[]
  { new M { P = 0 }, new M { P = 1 }, new M { P = 2 } };
  public static IEnumerable<M> S2()
  {
    for (int i = 0; i < 3; ++i)
      yield return ems[i];
  }

  public static IEnumerable<M> S3()
  {
    return new M[]
    { new M { P = 0 }, new M { P = 1 }, new M { P = 2 } };
  }

  private class X : IEnumerable<M>
  {
    public IEnumerator<X> GetEnumerator()
    {
      return new XEnum();
    }
    // Omitted: non generic version
    private class XEnum : IEnumerator<X>
    {
      int i = 0;
      M current;
      public bool MoveNext()
      {
        current = new M() { P = i; }
        i += 1;
        return true;
      }
      public M Current { get { return current; } }
      // Omitted: other stuff.
    }
  }

  public static IEnumerable<M> S4()
  {
    return new X();
  }

  public static void Add100(IEnumerable<M> items)
  {
    foreach(M item in items) item.P += 100;
  }
}
</code>```

All right, we have four methods. S1 and S2 are automatically generated sequences; S3 and S4 are manually generated sequences. Now suppose we have:

```<code>var items = C.Sn(); // S1, S2, S3, S4
S.Add100(items);
Console.WriteLine(items.First().P);
</code>```

The result for S1 and S4 will be 0; every time you enumerate the sequence, you get a fresh reference to an M created. The result for S2 and S3 will be 100; every time you enumerate the sequence, you get the same reference to M you got the last time. Whether the sequence code is automatically generated or not is orthogonal to the question of whether the objects enumerated have referential identity or not. Those two properties -- automatic generation and referential identity -- actually have nothing to do with each other. The article you linked to conflates them somewhat.

Unless a sequence provider is documented as always proffering up objects that have referential identity, it is unwise to assume that it does so.

Title: Detecting IEnumerable "State Machines"

Body:
Your question, as I understand it, seems to be based on an incorrect premise. Let me see if I can reconstruct the reasoning:

The linked-to article describes how automatically-generated sequences exhibit a "lazy" behaviour, and shows how this can lead to a counter-intuitive result.

Therefore I can detect whether a given instance of IEnumerable is going to exhibit this lazy behaviour by checking to see if it is automatically generated.

How do I do that?

The problem is that the second premise is false. Even if you could detect whether or not a given IEnumerable was the result of an iterator block transformation (and yes, there are ways to do that) it wouldn't help because the assumption is wrong. Let's illustrate why.

class M { public int P { get; set; } }
class C
{
  public static IEnumerable<M> S1()
  {
    for (int i = 0; i < 3; ++i)
      yield return new M { P = i };
  }

  private static M[] ems = new M[]
  { new M { P = 0 }, new M { P = 1 }, new M { P = 2 } };
  public static IEnumerable<M> S2()
  {
    for (int i = 0; i < 3; ++i)
      yield return ems[i];
  }

  public static IEnumerable<M> S3()
  {
    return new M[]
    { new M { P = 0 }, new M { P = 1 }, new M { P = 2 } };
  }

  private class X : IEnumerable<M>
  {
    public IEnumerator<X> GetEnumerator()
    {
      return new XEnum();
    }
    // Omitted: non generic version
    private class XEnum : IEnumerator<X>
    {
      int i = 0;
      M current;
      public bool MoveNext()
      {
        current = new M() { P = i; }
        i += 1;
        return true;
      }
      public M Current { get { return current; } }
      // Omitted: other stuff.
    }
  }

  public static IEnumerable<M> S4()
  {
    return new X();
  }

  public static void Add100(IEnumerable<M> items)
  {
    foreach(M item in items) item.P += 100;
  }
}

All right, we have four methods. S1 and S2 are automatically generated sequences; S3 and S4 are manually generated sequences. Now suppose we have:

var items = C.Sn(); // S1, S2, S3, S4
S.Add100(items);
Console.WriteLine(items.First().P);

The result for S1 and S4 will be 0; every time you enumerate the sequence, you get a fresh reference to an M created. The result for S2 and S3 will be 100; every time you enumerate the sequence, you get the same reference to M you got the last time. Whether the sequence code is automatically generated or not is orthogonal to the question of whether the objects enumerated have referential identity or not. Those two properties -- automatic generation and referential identity -- actually have nothing to do with each other. The article you linked to conflates them somewhat.

Unless a sequence provider is documented as always proffering up objects that have referential identity, it is unwise to assume that it does so.


问:
Why are custom PDF download options preferred over ctrl+p?
Why do I, as a developer, have to go through so much trouble developing PDF download options for my clients when everyone in the world can simply hit Ctrl+P and life is good?

The current issue I'm working on is dealing with Google Charts, so I'm not stating that offering PDF downloads in general is relatively difficult.  On the contrary, particular cases are more trouble than they seem to be worth.

See also: @media print {}

Update: With a little research, I was able to find a perfectly workable solution.  "Just hit Ctrl+P" now sounds like a ridiculous thing to say.  Thanks everyone for your input.

If you're interested to know what I decided to do, I realized that Google Charts are output as SVG markup and I think I should be able to use TCPDF to render them in a PDF document.

答: Web pages are not designed for print, they are designed to be rendered on a screen. As such, there's no guarantee that it will even fit within the dimensions of a standard paper size. Printing web pages to paper when they are not designed to fit on paper usually results in a mess. Giving your web application the ability to render important pages that a user might want a hard-copy of (such as receipts of banking transactions, or tickets to events) as printer-friendly PDF makes it much easier for people to produce those hard copies.</p>


答:
You dont 'have to' do anything.  But if you want to ensure the PDF looks exactly the same for each person who downloads it, you need to render it yourself.  Otherwise you're depending on various web browsers & print engines to render the PDF, and the results may not be that great.

And of course, you also cant assume that every device that might access the document is capable of printing or creating a pdf.

Title: Why are custom PDF download options preferred over ctrl+p?

Body:
Why do I, as a developer, have to go through so much trouble developing PDF download options for my clients when everyone in the world can simply hit Ctrl+P and life is good?

The current issue I'm working on is dealing with Google Charts, so I'm not stating that offering PDF downloads in general is relatively difficult.  On the contrary, particular cases are more trouble than they seem to be worth.

See also: @media print {}

Update: With a little research, I was able to find a perfectly workable solution.  "Just hit Ctrl+P" now sounds like a ridiculous thing to say.  Thanks everyone for your input.

If you're interested to know what I decided to do, I realized that Google Charts are output as SVG markup and I think I should be able to use TCPDF to render them in a PDF document.


答:
In addition to the other answers, there is the fact that a great many people can't just hit ctrl-p -- for instance, I'm typing this on an iPad and do not have a printer that I can use from it.  But I can save a pdf in GoodReader or DropBox and later transfer it to a computer with a printer.

In addition, the user may not want a hard copy so much as a permanent record -- if I save something as a pdf, I can name it and store it where I can find it later (even without internet access).  If I rely upon you as the company to keep track of it for me, then I'm in trouble when you keep it for X months and I need it X+1 months later (just had this exact problem with a copy of a check, kept online for 120 days, needed it after that.  Fortunately, I FIRST needed it within the limit so I made a copy).


答:
The reason design principles are so helpful and why it's unfortunate people conflate them with patterns is because a design priciple is simply that; a principle for design; all design.

You can and should apply design principles to all things that require design, they're truly cross-cutting (buzzwords yay!).

For example, Principle of Least Astonishment was created and described always for UI designers to ensure they present a UI that doesn't cause users to make mistakes. It can however be applied to all contract definitions by developers, it can really be applied to anything, that's why the classic example is the elevator button; one with an up arrow that calls the elevator to go down is poor design.

If design principles can be applied to a UI, and an elevator, then honestly anything that is to be designed can have them applied. Imagine if a car's roll-down-window button also turned on the vent because it thinks you want fresh air, sounds like bad design right? Single responsibility principle; any buttons in a car that do multiple things would just seem weird to a user.

Even LSP can be defined beyond code, think about a common type of thing? Say a taxi cab. Now for a taxi cab you call them and they show up when you request, a taxi cab that is always 15 minutes late violates LSP because you always expect all taxi cabs to be on-time, if you expected them all to be 15 minutes late it wouldn't violate LSP because it would follow the rules of the common-type taxi cab.

Open-Closed principle is observable in the design of cars, they have a base model closed for modification but open for extension with a roof rack, keyless entry, clear-coat, side runners etc. The vehicle was designed to allow for those extensions, but it was designed to be closed for modification which is why it takes a mechanic to change the drive-train to AWD and isn't easy even for him. It wasn't designed to be modified in this way, but it was designed with relevant extension points.

Full-scale systems themselves at a macro level should definitely take these into account, a single process service that is side-effect free with a single responsibility is great to have for certain things and follows many of these, have as many of those as you want. A service that does a ton of things all on it's own is however a violation of SRP.

Title: Can I apply SOLID concepts to entire solution designs rather than just the internal components?

Body:
So maybe the quick answer is 'Yes' absolutely (or no I suppose), but let me explain my question angle to get a better derived answer.

We all commonly use SOLID design principals when making up the pieces and parts of our applications. Don't make a class do too many things, don't make an Interface too large, use abstraction not concretions, etc.

Is it OK to apply this mentality at an abstract level when thinking about solutions, services, etc.? The main problem: I'm struggling with the request to have a single service do all things related to a specific business domain. Add to this multiple teams would all have their hands in the pot of the same application to add whatever functionality needed.

I have a service being built out with many good architecture and design principals in mind and  believe totally that lots of 'additional' functionality could be bolted on vertically within the same framework and solution. After all this one of the reasons why we spend time architecting solutions to be loosely coupled and allow scalability with rather ease. So you might say, "go for it, if the framework can handle it then add away!"

Something is not sitting right with me and I would be concerned with a behemoth of an application/service that tries to do everything. I tried doing searches about "applications that do too much" or "services that have too many responsibilities" but not much came up. When I start thinking about the SOLID principals, I think having a service that does everything related to a specific business domain might not be a good idea and may cause issues on down the road with maintainability and stepping on each other's toes.

Is it correct to use SOLID principals when looking at entire solution functionality? Is creating a service like http://www.mycompany.com/api/[everyMethodPossible] correct, or could I be doing something that is incorrect?

Thanks!


答:
If you are using C/C++ then the preprocessor could provide readability.</p>

```<code>#define NOT !

if(_someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue &&
    NOT _someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant)
{
    //Do something
}
</code>```

Title: Emphasize negation

Body:
If you are using C/C++ then the preprocessor could provide readability.

#define NOT !

if(_someViewModelNameThatIsLong.AnotherPropertyINeedToCheck == someValue &&
    NOT _someViewModelNameThatIsLong.ThisIsABooleanPropertyThatIsImportant)
{
    //Do something
}


答:
The rationale behind this recommendation is that you want to be able to use the same precomputation elsewhere in your application. See Replace Temp with Query in refactoring patterns catalog:

The new method can then be used in other methods

```<code>    double basePrice = _quantity * _itemPrice;
    if (basePrice > 1000)
        return basePrice * 0.95;
    else
        return basePrice * 0.98;
</code>```

```<code>    if (basePrice() > 1000)
        return basePrice() * 0.95;
    else
        return basePrice() * 0.98;
...
double basePrice() {
    return _quantity * _itemPrice;
}
</code>```

Thus, in your host and URI example, I would only apply this recommendation if I plan to reuse the same URI or host definition.

If this is the case, due to namespace, I won't define a global uri() or host() method, but a name with more information, like twilio_host(), or archive_request_uri().

Then, for line length issue, I see several options:

Create a local variable, like uri = archive_request_uri().

Rationale: In the current method, you want the URI to be the one mentioned. The URI definition is still factorized.

Define a local method, like uri()  { return archive_request_uri() }

If you often use the Fowler's recommendation, you'd know that the uri() method is the same pattern.

If due to language choice you need to access local method with a 'self.', I'd recommend the first solution, for increased expressiveness (in Python, I'd define the uri function inside the current method).

Title: Temporary variables vs line length requirements

Body:
I've been reading Martin Fowler's Refactoring. It is generally excellent but one of Fowler's recommendations seems to be causing a little trouble.

Fowler recommends that you replace temporary variables with a query, so instead of this:

```<code>double getPrice() {
    final int basePrice = _quantity * _itemPrice;
    final double discountFactor;
    if (basePrice > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice * discountFactor;
}
</code>```

you pull out into a helper method:

```<code>double basePrice() {
    return _quantity * _itemPrice;
}

double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice() * discountFactor;
}
</code>```

In general I agree except that one reason I use temporary variables is when a line is too long. For example:

```<code>$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);
</code>```

If I tried inlining that, the line would go longer than 80 characters.

Alternately I end up with chains of code, which are themselves not that much easier to read:

```<code>$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));
</code>```

What are some strategies for reconciling the two?

Body:
The rationale behind this recommendation is that you want to be able to use the same precomputation elsewhere in your application. See Replace Temp with Query in refactoring patterns catalog:

The new method can then be used in other methods

    double basePrice = _quantity * _itemPrice;
    if (basePrice > 1000)
        return basePrice * 0.95;
    else
        return basePrice * 0.98;

    if (basePrice() > 1000)
        return basePrice() * 0.95;
    else
        return basePrice() * 0.98;
...
double basePrice() {
    return _quantity * _itemPrice;
}

Thus, in your host and URI example, I would only apply this recommendation if I plan to reuse the same URI or host definition.

If this is the case, due to namespace, I won't define a global uri() or host() method, but a name with more information, like twilio_host(), or archive_request_uri().

Then, for line length issue, I see several options:

Create a local variable, like uri = archive_request_uri().

Rationale: In the current method, you want the URI to be the one mentioned. The URI definition is still factorized.

Define a local method, like uri()  { return archive_request_uri() }

If you often use the Fowler's recommendation, you'd know that the uri() method is the same pattern.

If due to language choice you need to access local method with a 'self.', I'd recommend the first solution, for increased expressiveness (in Python, I'd define the uri function inside the current method).


问:
How can I present some printed Visual Basic source code in an aesthetically pleasing manner?
Right now I'm interning at a major engineering company. I'll be leaving in a few months though, so my project manager has requested a print out of my source code for a VBA project I've been working on.

He would like to have it reviewed to make sure I didn't do anything ridiculous, and to make sure it's organized well enough for someone to maintain easily enough once I'm gone.

I'm not really sure why he would want a print out instead of files, but since the VBA editor is ugly as sin this is probably a good thing.

I would like to make an impression with this - however minor - so my question is how can I make this look professional? I.e., maybe there are certain fonts that make sense here, perhaps I could apply a color scheme to the words, etc?

答:
"... a print out of my source code ..." - Don't bother. He probably won't even read it. I've had managers like that in the past - a long way in the past ... in old government departments ... who had no idea what programming was about - even then.

If you really want to do this, just dump your code and forget it. I suspect he's either deliberately messing with you or is totally 404. In either case, impressing him will not benefit you in any way and a request like that would be enough for me to put that company on my "Never want to work there list".