问:
Is Code First with Migrations or SQL Server Data Tools a better fit?
I have been given a spec to create a new MVC4 website, it will not be too large a project at first but I suspect it will grow as the business gets new ideas for it.

Using .NET 4.5 ASP.NET MVC4 and EF I have to choose between code-first with migrations or Sql Server Data Tools (SSDT) for handling my database.

With the SSDT I can control my database in a project as part of my solution and handle the changes all the way from dev through to production and beyond using dacpac files. My experience of code-first from MVC3 was not to use it beyond development due to the limited database options. It would always end up with dropping the Db on model change or handle the Db changes manually. However I am led to believe with MVC4 Migrations that is no longer the case and I can now push updates to the Db.

So my question is which one is the most efficient to use based on saving time/effort in development but also scalable and able to handle production changes. I liked code-first and the ability to generate my Database from Models, does the introduction of migrations now make it viable in production?

答:
My personal opinion is that codefirst great tool and great for development. The steps of databasefirst development should be scripting external tools or by hand, if you already have a production database.

The codefirst to be included in the development of database version control system and provides a distributed database development.

Starting point, it's a good series:

http://coding.abel.nu/2012/02/using-entity-framework-to-create-a-database/


问:
Application of Implementing 3 Stacks in single array
Well, there is lot of discussion about implementing 3 (or 2 stacks) in a single array. But whats the real need or application for implementing stacks like that?

Can't we allot memory as 3 separate stacks [array] itself? Anyway we are alloting array[size * 3] in that single array.

some links that discuss some:

Use an array to implement three Stack

how to implement 3 stack in a single array efficiently?

答:
Implementing multiple stacks in a single (linked list) array could use memory more efficiently.

If you have three stacks in three separate arrays, each one would need pre-allocated space to allow for future elements, and each one would need new memory to be allocated if it fills up.  Combining them to a single array would reduce the amount of "extra" memory that is pre-allocated for future operations, and you would have to allocate new memory fewer times.

However, the stacks in a single array would also be more complicated to manage.  Elements of the three stacks will be interspersed with each other.  When elements are removed from one stack, it may leave gaps.  You then need to be able to search and fill these gaps later on when you add a new element.

With the amount of memory typically available these days, combining stacks in this way would be a rather extreme optimization.  Rarely would you even think of doing this.  But it might be useful occasionally.

Update: It would be most useful in certain specialized cases.  If you have a situation in which you will frequently move elements between stacks, storing the stacks in a single array would be more efficient.  Moving element X from stack A to stack B would only require changing the links.

ContentLicense: CC BY-SA 3.0


问:
How to deal with database connections in a Python library module
I have created a library in Python that contains functions for accessing a database. This is a wrapper library around a third party application database, written due to the fact that the third party application does not offer a decent API. Now I originally let each function open a database connection for the duration of the function call which was OK, until my program logic used nested calls to the functions where I would then be calling a particular function a few thousand times. This wasn't very performant. Profiling this showed that the overhead was in the database connection setup - once per function call. So I moved the open connection from within the function(s) to the module itself, so that the database connection would be opened when the library module was imported. This gave me an acceptable performance.

Now I have two questions regarding this. Firstly, do I need to be concerned that I am no longer explicitly closing the database connection and how could I do it explicitly with this set-up? Secondly, does what I have done fall anywhere close to the realm of good practice and how might I otherwise approach this?

答:
It really depends on the library you're using. Some of them could be closing the connection on their own (Note: I checked the builtin sqlite3 library, and it does not).  Python will call a destructor when an object goes out of scope, and these libraries might implement a destructor that closes the connections gracefully.

However, that might not be the case!  I would recommend, as others have in the comments, to wrap it in an object.

```<code>class MyDB(object):

    def __init__(self):
        self._db_connection = db_module.connect('host', 'user', 'password', 'db')
        self._db_cur = self._db_connection.cursor()

    def query(self, query, params):
        return self._db_cur.execute(query, params)

    def __del__(self):
        self._db_connection.close()
</code>```

This will instantiate your database connection at the start, and close it when the place your object was instantiated falls out of scope. Note: If you instantiate this object at the module level, it will persist for your entire application.  Unless this is intended, I would suggest separating your database functions from the non-database functions.

Luckily, python has  standardized the Database API, so this will work with all of the compliant DBs for you :)

Body:
It really depends on the library you're using. Some of them could be closing the connection on their own (Note: I checked the builtin sqlite3 library, and it does not).  Python will call a destructor when an object goes out of scope, and these libraries might implement a destructor that closes the connections gracefully.

However, that might not be the case!  I would recommend, as others have in the comments, to wrap it in an object.

class MyDB(object):

    def __init__(self):
        self._db_connection = db_module.connect('host', 'user', 'password', 'db')
        self._db_cur = self._db_connection.cursor()

    def query(self, query, params):
        return self._db_cur.execute(query, params)

    def __del__(self):
        self._db_connection.close()

This will instantiate your database connection at the start, and close it when the place your object was instantiated falls out of scope. Note: If you instantiate this object at the module level, it will persist for your entire application.  Unless this is intended, I would suggest separating your database functions from the non-database functions.

Luckily, python has  standardized the Database API, so this will work with all of the compliant DBs for you :)


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
I think it is to do with the close correlation between the functional programming paradigm and programming for the web.

Ruby on Rails brought the whole functional programming approach into sharp relief since it offered a very quick path to a functional (heh heh) web application. There is an interesting discussion on SO about this, and one particular answer stands out:

Functional programming matches web
  apps very well. The web app recieves a
  HTTP request and produces a HTML
  result. This could be considered a
  function from requests to pages.

Compare with desktop apps, where we
  typically have a long running process,
  a stateful UI and dataflow in several
  directions. This is more suited to OO
  which is concerned about objects with
  state and message passing.

Given that functional programming has been around for ages, I wonder why I don't see many job adverts looking for Lisp developers for greenfield web projects.

ContentLicense: CC BY-SA 2.5


答:
Many interview questions serve no practical purpose. They are a challenge to see if you can think your way through something difficult. People who ask them believe they serve as a good substitute for the genuinely difficult challenges in their coding that cannot be explained in such a short time (and whose solutions cannot be evaluated so quickly either.)

In Physics there's a story about the question "how would you measure the height of a building with a barometer?" The "right" answer involves measuring the air pressure at the top and bottom and applying a formula. My favourite "wrong" answers involve dropping it from the top, measuring the time till it hits the ground, and applying a formula, or seeking out the architect/janitor/owner of the building and offering a trade: I'll give you this expensive barometer if you tell me how tall that building is.

The point of the question wasn't that people need to measure height with barometers regularly (or ever) but to see if the candidate knew the formula for pressure and height. Similarly your question will test if you know how to manage memory, restructure a simple approach (stacks) to handle a strange constraint, and think about clever things like not moving the item from stack to stack but just updating the links. While there may be some strange edge case like "each stack can have up to a million items, but when one grows the others shrink so the total space never changes" that happen in the real world, that is not why you're being asked to solve the problem.

Title: Application of Implementing 3 Stacks in single array

Body:
Well, there is lot of discussion about implementing 3 (or 2 stacks) in a single array. But whats the real need or application for implementing stacks like that?

Can't we allot memory as 3 separate stacks [array] itself? Anyway we are alloting array[size * 3] in that single array.

some links that discuss some:

Use an array to implement three Stack

how to implement 3 stack in a single array efficiently?


问:
How do you hide error handling?
Many people consider exceptions to be a problem because they create invisible paths through your code. For example in this snippet:

```<code>function writeToFile(text, filename):
  filehandle = open(filename)
  foreach line in text:
    filehandle.write(line)
  filehandle.close()
</code>```

The write method could throw an Exception. In that case the function will end prematurely and the filehandle is not closed. Writing exception safe code is hard.

On the other hand adding explicit error handling like in C clutters up the code considerably. (This seems to be the "other" option if you don't like exceptions.)

```<code>function writeToFile(text, filename):
  filehandle = open(filename)
  if nullptr == filehandle:
    return
  foreach line in text:
    if(!filehandle.write(line)):
      filehandle.close()
      return
  filehandle.close()
</code>```

Now this is just a simple example. I just wrote code to do some logging and between the abstract concept of "Just dump data into a file!" and my implementation is a difference of about 200 lines.

So what do people do to keep their code readable in spite of all those corner cases that they need to watch out for and handle?

Do we have to resort to literate programming? :)

答:
```<code>function writeToFile(text, filename):
  filehandle = open(filename)
  if (filehandle)
  {
    foreach line in text:
      if(!filehandle.write(line)):
        break;

    filehandle.close()
  }
</code>```

that's not so bad, and does everything you wanted, with error handling.

Or:

```<code>function writeToFile(text, filename):
  filehandle = open(filename)
  try
  {
    foreach line in text:
      filehandle.write(line)
  }
  catch (...)
  {
  }
  filehandle.close()
</code>```

again, not too bad and would be better in a larger function.

I think the issue here is not so much error handling, which is an important and necessary part of coding, as much a part of coding and the 'functional' code, but the mindset that says it needs to be hidden or that the error handling code is somehow a dirty secret that has to be kept out of sight. You have to put lots of other stuff in there  (eg logging) that will bloat your code up.

Perhaps the best approach for you is to use C/C++ and use macros to keep your "extraneous" code to single-line statements. Or just to learn to love error handling code.

Title: How do you hide error handling?

Body:
function writeToFile(text, filename):
  filehandle = open(filename)
  if (filehandle)
  {
    foreach line in text:
      if(!filehandle.write(line)):
        break;

    filehandle.close()
  }

that's not so bad, and does everything you wanted, with error handling.

Or:

function writeToFile(text, filename):
  filehandle = open(filename)
  try
  {
    foreach line in text:
      filehandle.write(line)
  }
  catch (...)
  {
  }
  filehandle.close()

again, not too bad and would be better in a larger function.

I think the issue here is not so much error handling, which is an important and necessary part of coding, as much a part of coding and the 'functional' code, but the mindset that says it needs to be hidden or that the error handling code is somehow a dirty secret that has to be kept out of sight. You have to put lots of other stuff in there  (eg logging) that will bloat your code up.

Perhaps the best approach for you is to use C/C++ and use macros to keep your "extraneous" code to single-line statements. Or just to learn to love error handling code.


答:
I don't see anything wrong with code such as the second example.  The details could probably be improved a little bit, but, yes, a lot of code ends up being error handling, data verification, and the like.  This is essential to writing good code.

It would be a mistake to view it as "extra stuff" that gets in the way of the real work.  Such a mindset is likely to lead to inadequate error checking.

I once worked on some aviation software in which the core algorithm probably could have been written in about 50 lines.  This was surrounded by thousands of lines that existed primarily for error checking and correction.  This may be annoying, but it is rather essential for an function like keeping a plane in the air.

Title: How do you hide error handling?

Body:
Many people consider exceptions to be a problem because they create invisible paths through your code. For example in this snippet:

```<code>function writeToFile(text, filename):
  filehandle = open(filename)
  foreach line in text:
    filehandle.write(line)
  filehandle.close()
</code>```

The write method could throw an Exception. In that case the function will end prematurely and the filehandle is not closed. Writing exception safe code is hard.

On the other hand adding explicit error handling like in C clutters up the code considerably. (This seems to be the "other" option if you don't like exceptions.)

```<code>function writeToFile(text, filename):
  filehandle = open(filename)
  if nullptr == filehandle:
    return
  foreach line in text:
    if(!filehandle.write(line)):
      filehandle.close()
      return
  filehandle.close()
</code>```

Now this is just a simple example. I just wrote code to do some logging and between the abstract concept of "Just dump data into a file!" and my implementation is a difference of about 200 lines.

So what do people do to keep their code readable in spite of all those corner cases that they need to watch out for and handle?

Do we have to resort to literate programming? :)


答:
In a language that supports deterministic destruction:

```<code>function writeToFile(text, filename):
  filehandle = open(filename)
  foreach line in text:
    filehandle.write(line)
</code>```

and the type of filehandle just closes itself in the destructor. This is how it works in C++.

Languages without deterministic destruction often have syntactic constructs for scoped resources: using-block in C#, try-with-resources in Java, with-block in Python:

```<code>function writeToFile(text, filename):
  with open(filename) as filehandle:
    foreach line in text:
      filehandle.write(line)
</code>```

If they don't (Java <7), there will be something like a try...finally construct instead. And if that doesn't exist either, don't use that broken language.

Languages with a focus on closures (Ruby, most functional languages, like Haskell) often use the around-pattern instead - sorry for abandoning the python-like syntax here:

```<code>function writeToFile(text, filename) {
  withOpenFile(filename, lambda(filehandle) {
    foreach line in text {
      filehandle.write(line)
    }
  })
}
</code>```

Bottom line is that you want some support from the language for ensuring that some code is executed no matter how you leave a block.

Keep in mind that what this is talking about is not really error-handling. This is about exception-safety: code doing the right thing when an exception is thrown. You still have to actually deal with the exception somewhere, but this is not about that.

Title: How do you hide error handling?

Body:
In a language that supports deterministic destruction:

function writeToFile(text, filename):
  filehandle = open(filename)
  foreach line in text:
    filehandle.write(line)

and the type of filehandle just closes itself in the destructor. This is how it works in C++.

Languages without deterministic destruction often have syntactic constructs for scoped resources: using-block in C#, try-with-resources in Java, with-block in Python:

function writeToFile(text, filename):
  with open(filename) as filehandle:
    foreach line in text:
      filehandle.write(line)

If they don't (Java <7), there will be something like a try...finally construct instead. And if that doesn't exist either, don't use that broken language.

Languages with a focus on closures (Ruby, most functional languages, like Haskell) often use the around-pattern instead - sorry for abandoning the python-like syntax here:

function writeToFile(text, filename) {
  withOpenFile(filename, lambda(filehandle) {
    foreach line in text {
      filehandle.write(line)
    }
  })
}

Bottom line is that you want some support from the language for ensuring that some code is executed no matter how you leave a block.

Keep in mind that what this is talking about is not really error-handling. This is about exception-safety: code doing the right thing when an exception is thrown. You still have to actually deal with the exception somewhere, but this is not about that.


答:
No doubt about it, clean error handling is hard without cluttering up code. Although not ideal, I try to put a try catch block in the base function I am calling. For example, if I have a basic console application that is set up as follows (not meant to be language specific, just an example):

Main() {
 myFunction();
};

myFunction() {
 // do stuff
};

putting a try catch block inside main will catch any errors that occur in myFunction. Regretfully this is not always guaranteed to work for every style of program, and will present difficulties when dealing with code that does not get called from the same location (in the above example Main). For languages like javascript, where you can pass a function as a parameter, you can write a simple wrapper function that simply calls a function that was passed to it inside a try catch block and returns the result.

Where and how to gracefully catch errors is also partly dependent on how your program logic is set up. If most of the code that could produce errors is located in a separate class it could be better to handle the error in the class itself and not worry about throwing it to the caller.

In general, I try to put a try catch block in my base functions (such as Main in the example), and an additional try catch block anywhere that actions need to be taken on error, such as closing a file reader. For the most part that will catch most errors that occur (once again depending on how the code executes), and will provide additional security when needed.

Title: How do you hide error handling?


问:
Over thinking development
I've been working as an app developer for a year and a half now (not long I know), and I've just been given my first big project.

Needless to say it didn't go very smoothly, so I sought advice from a senior programmer involved in the project about how to approach it.

He said that I had drastically been over thinking the task at hand, and that because I had never tackled a project of this scale before I'd been spending too much time over thinking design patterns. In his wise words, he told me "F*ck the future, build for now".

Is this a trend programmers typically follow when going about a project like this? For example, if you were asked to do a proof of concept model, is it a typical trend just to mash a workable example out as soon as possible?

Edit: In light of the debate this has sparked, I'd like to mention that this situation is fairly extreme: we have very tight deadlines due to factors beyond our control (i.e. the market we're aiming for will lose interest if we don't show them something) and his advice proved to be very effective for this particular task.

答:
Do programmers typically build something that works now without thinking about the future?

Yes.

Should they do so?

No.

At a first glance it would seem that "thinking about the future" violates established design principles like KISS and YAGNI, which claim that there shouldn't be implemented anything that isn't required right now.

But actually it doesn't. Thinking about the future means designing simple, extensible and manageable software. This is especially important for long-term projects. New features will be required with time, and having a solid design will make it easier to add new pieces.

Even if you aren't going to work on a project after you complete it, you should still develop it intelligently. Its your work, and you should do it well, at least in order not to forget how good work is done.

Title: Over thinking development


答:
Design is usually open-ended so it is way too easy to apply too much or too little of it. And you will know the correct amount only after the project is done or discarded. Or even not then.

There's no general recipe for success, but you can learn to recognize extremes. Complete design of everything up front hardly ever works beyond trivial stuff. It's okay to leave components for refining and just have a feeling that it can be done, or there's a way to discover problems early.

You may look up how incremental development works if you're not familiar. Successful methods usually are iterative on one or more levels, seek tight feedback and grow on some skeleton.

Title: Over thinking development

Body:
I've been working as an app developer for a year and a half now (not long I know), and I've just been given my first big project.

Needless to say it didn't go very smoothly, so I sought advice from a senior programmer involved in the project about how to approach it.

He said that I had drastically been over thinking the task at hand, and that because I had never tackled a project of this scale before I'd been spending too much time over thinking design patterns. In his wise words, he told me "F*ck the future, build for now".

Is this a trend programmers typically follow when going about a project like this? For example, if you were asked to do a proof of concept model, is it a typical trend just to mash a workable example out as soon as possible?

Edit: In light of the debate this has sparked, I'd like to mention that this situation is fairly extreme: we have very tight deadlines due to factors beyond our control (i.e. the market we're aiming for will lose interest if we don't show them something) and his advice proved to be very effective for this particular task.


问:
What are the differences among the .NET certification exams?
I am a .NET developer using WPF and ASP.NET MVC and I was hoping to pass some kind of certification exam.

There seems to be four exams but I am unable to understand what the differences are even with Microsoft's definitions:

MCPD

MCAD

MCSD

MTA

How do they relate to each other? Is there a natural progression path through the certification exams? What version of .NET are they suited for?

答:
As of  Jun 5 '13:

Looks to me like the path is MCSA > MCSE. MCSA has been around since Windows 2000, maybe even NT.  If you were going for something like SharePoint development, you'd probably start by being an MCSA on Windows Server 2012, then becoming an "MCSE: SharePoint":

MCSA, Windows Server 2012:

70-410:  Installing and Configuring Windows Server 2012

70-411:  Administering Windows Server 2012

70-412:  Configuring Advanced Windows Server 2012 Services

MCSE: SharePoint 2013:

70-331:  Core Solutions of Microsoft SharePoint Server 2013

70-332:  Advanced Solutions of Microsoft SharePoint Server 2013

(http://www.microsoft.com/learning/en/us/mcse-sharepoint-certification.aspx#fbid=tqfR4CMqXo5)

The MCM/MCSM path for SP 2010 is expiring and does not yet include exams for SP 2013.  The path is MCTS > MCM.  These have to be completed by Aug. 1, 2013.

MCM/MCSM: SharePoint 2010:

70-667: TS: Microsoft SharePoint 2010, Configuring

70-573: TS: Microsoft SharePoint 2010, Application Development

70-668: PRO: Microsoft SharePoint 2010, Administrator

70-576 : PRO: Designing and Developing Microsoft SharePoint 2010 Applications

(SP 2010: http://www.microsoft.com/learning/en/us/mcm-certification.aspx#fbid=tqfR4CMqXo5)

(SP 2013: http://www.microsoft.com/learning/en/us/mcsm-sharepoint-certification.aspx#fbid=tqfR4CMqXo5)

Updates/Changes, 5/19/2017:

MCSE: SharePoint

As quoted from Microsoft:

Note This certification retired on March 31, 2017. Find out about the replacement certification, MCSE: Productivity.

Reference: https://www.microsoft.com/en-us/learning/mcse-sharepoint-certification.aspx#fbid=tqfR4CMqXo5

Taken from that MCSE: Productivity site, it says your path begins by taking "one of the following MCSA certifications: MCSA Office 365, MCSA Windows Server 2012 (as described earlier, far above), or MCSA Windows Server 2016" first.

MCM - MCSM - MCA

As quoted from Microsoft:

All Microsoft Certified Master (MCM), Microsoft Certified Architect (MCA), and Microsoft Certified Solutions Master (MCSM) certification exams were retired on January 1, 2014.

Reference: https://www.microsoft.com/en-us/learning/mcsm-certification.aspx#fbid=tqfR4CMqXo5

Original Question

For the original certs in the original question:

MCPD

MCAD

MCSD

MTA

MCPD:

As quoted from Microsoft:

Microsoft Certified Professional Developer (MCPD) certifications will not be updated for versions later than Visual Studio 2010, and your MCPD certification will decline in value as companies move to newer versions of our products.

In other words, IMHO, don't bother.  Visual Studio in my shop already uses 2015, so technically the certification is useless to prove you know the tool-at least the changes that have been made to it, which have been enough since 2010 to possibly make an employer question if you're up on the latest methods.

Reference:  https://www.microsoft.com/en-us/learning/mcpd-certification.aspx

MCAD / MCSD:

This used to be the path to saying you were an applications developer, then a solutions developer.  MCAD, and MCSD .NET, are now listed as legacy (retired) certifications by Microsoft at https://www.microsoft.com/en-us/learning/retired-certifications.aspx, under Visual Studio certifications, but then if you go to the Microsoft Learning home page and click Certifications & Exams > About certifications > Certification overview, and you go to "App Builder", it still lists MCSD as the top tier, with MCSA and MTA as its predecessors.  So actually appears

MTA -> MCSA -> MCSD

to be the path they intend people to take, except....

MTA:

The new Microsoft Technology Associate certificate is now a starting point for being a certified developer, if you are new to the field.  You have various MTAs:  Mobility (database development), App Builder (full system applications), and IT Infrastructure (includes cloud-based, desktop, and server infrastructure).  MTA is NOT a prerequisite for MCSA/MCSD, the next 2 rungs.

I would suggest not to bother, since it's not required.

Reference:  https://www.microsoft.com/en-us/learning/mta-certification.aspx

New Certification Path:

MTA being optional leaves MCSA, and then MCSD as your path to success for an App Builder.  For other paths they preface it with MTA (not required) and end it with another cert, an MCSE (note that MCSE: SharePoint is now retired and is now MCSE: Productivity).  It depends now on what type of developer you want to be, out of these new categories:

Mobility

Cloud

Productivity

Data

App Builder

Business

Based on that dictates if you have MCSE at the end or not.  I feel it's optional and is that extra thing, like the Master certifications used to be, for the MCSE, and that MCSA and MCSD should be good enough.

Reference:  https://www.microsoft.com/en-us/learning/certification-overview.aspx#/

(Note: MCSE used to stand for Microsoft Certified Systems Engineer for that particular technology, but is now Microsoft Certified Solutions Expert.)

OwnerDisplayName: John Mitchel


问:
How my website should use its own API?
Im building small web-service which will provide my users with data through API.
Also, some data will be available right on my website.

The question is about how to use my own API? Should my website make a query to, for example, http://website.com/api/users/?format=json and then render data? Because I can use standard Django ORM features, but this is not corresponding with using of own API.

update:
Imagine that I have a database full of games with release date, game name, game platform etc. And on my own website I will show this games as a list or a grid. Also, this data can be reached through API in JSON format, this data can be updated through API and even deleted. And on my own website I have html forms that allow me to do this actions in a user-friendly way. So how should I access my own API? Via POST request to my API or via django ORM directly to database?

答:
Without understanding how your web-service is set up and how web methods are intended to be called, I don't think there is a way to say you should implement it in a specific way.

For best practice and practicality, I would implement it as close to the way you intend developers to consume/implement it as possible.

Title: How my website should use its own API?


问:
Is it bad programming practice to check if a class referenced by its interface is an instance of another class?
I have a class (Timer) with an array list of Timable  objects. Timeable is an interface. There is some specific functionality that I need for the Trigger class (implements Timable), which has a reference called target. A lot of methods need to search through the Timer array for Trigger objects with a certain target.

What I did was a function like this:

```<code>public Timable[] findObjectsWithTarget(Cue target) {
    ArrayList<Timable> result = new ArrayList<Timable>();
    for (Timable timed : fireable) { //fireable is the array (actually a HashSet) of Timed objects
        if (timed instanceof Trigger && ((Trigger) timed).getTarget() == target)
            result.add(timed);
    }
    return (Timable[]) result.toArray();
}
</code>```

This feels like a bad practice. The Timer class is now dependent on the Trigger class (sort of) and are no longer generalized.

So, my two questions:

1) Is it actually a  bad practice? Why or why not?

2) What's a better way if it is a bad practice?

答:
Yes this is indeed a bad practice. You are using an interface to abstract your code from the implementation. When you work with the interface and access the implementation (via casting) you are violating the interface definition.

To solve this kind of problem extend your interface by another method, that you would access from within your code.

```<code>public Timable[] findObjectsWithTarget(Cue target) {
    ArrayList<Timable> result = new ArrayList<Timable>();
    for (Timable timed : fireable) { //fireable is the array (actually a HashSet) of Timed objects
        if (timed.hasTarget(target))
            result.add(timed);
    }
    return (Timable[]) result.toArray();
}
</code>```

You have to implement that method also in Timerclass but you can return false per default.

Body:
Yes this is indeed a bad practice. You are using an interface to abstract your code from the implementation. When you work with the interface and access the implementation (via casting) you are violating the interface definition.

To solve this kind of problem extend your interface by another method, that you would access from within your code.

public Timable[] findObjectsWithTarget(Cue target) {
    ArrayList<Timable> result = new ArrayList<Timable>();
    for (Timable timed : fireable) { //fireable is the array (actually a HashSet) of Timed objects
        if (timed.hasTarget(target))
            result.add(timed);
    }
    return (Timable[]) result.toArray();
}

You have to implement that method also in Timerclass but you can return false per default.


答:
When you start out programming, everything is a proof of concept even if it is just to yourself. There are cases when an idea requires something quick and dirty or a prototype because time is a key factor. The massive fear among developers is stakeholders thinking the little app is ready for production or you should be able add features at the same rate forever. You work on a large project and find out this isn't the case.

Large projects usually have more complex requirements, so there is a temptation to try and implement complex designs. You'll spend a lot of time reading, researching and trying to implement them. This can become a big time waster, but it is all part of learning and gaining experience. Knowing when to use a particular design is difficult and usually comes with experience. I tried "that" on "this" project and it didn't work but now I see it should work over "here".

You have to plan and plan a lot, but don't do it all at once. It definitely doesn't have to be done all at the beginning. I'd rather see someone create their first large project like this:

Design and discuss a little bit.

Write a bunch of code that does something.

Recognize the problems and STOP coding.

Get serious about design and stop worrying about losing momentum or your code-mojo and ignore the project manager (You're doing him/her a favor.).

Get the project under control. Fix your messes. Make sure everyone understands the plan. Keep the project under control.

Sometimes you hit one of those features that really makes you concerned on how to implement it in the existing codebase. This is not the time to "just make it work". I had a boss who said, "Sometimes you have to grab a stool instead of a hammer." He told me this after he caught me "thinking" at my desk. Unlike a lot of bosses, he didn't assume I was goofing-off and made sure I understood he wanted me to do more of it. Genius.

Ultimately, your code is the design. It is supported by documents, diagrams, meetings, email, whiteboard discussions, SO questions, arguments, cussing, fits of rage and quiet chats over coffee. There is a point where you can't design any more and risk having to throw more design time away because of the flaws you will only discover trying to write the code. Also, the more code you write the better chance you will introduce a design flaw that you can't code your way out of. Time for the stool again.

Title: Over thinking development


问:
How would you get all your expectations done within a user story?
I'm setting up some requirements for a software extension and try to use user stories to describe what I want to achieve.

As a creator I want to add a new entry, to let users access it through the main page.

I have the idea of adding an entry via Drag&Drop. My company has some guidelines, to have every command always available via context menu and ribbon.

Should I split up my origin story into separate actions?

As a creator I want to drag a new entry onto the main page, to let users access it.

As a creator I want to create a new entry on the main page via ribbon, to let users access it.

As a creator I want to create a new entry on the main page via context menu, to let users access it.

That approach would result in at least three user stories per feature what won't feel comfortable to me.

I could add these expectations during the discussion, but then it seems like giving a "way-to-follow" for developers.

So how would I ensure that the required quality/user experience is achieved?

答:
I think its wrong to divide the user-story into 3 pieces. You mentioned that every command should be accessible from 3 places. That can be pre-assumed in the user stories for new commands (or explicitly mentioned in every such user story).

If you need to divide it because development will implement those as separate tasks, IMO something isn't designed well in the back-end.

A user story as a rule represents a complete feature. And I wouldn't consider the feature complete unless the new command is accessible from every place required. Moreover, I would include accessibility in the command development user story itself.

As what comes for achieving the required quality, that's what testing is done for.


答:
It's my understanding that in Agile, a user story should be completed and tested in a single sprint.

With that in mind, I would not start by making separate stories, but just make one and outline the various pieces within it.

If after estimation (during planning) it's determined that the story will extend beyond a single sprint, split it into multiple with a common parent.

Title: How would you get all your expectations done within a user story?

Body:
I'm setting up some requirements for a software extension and try to use user stories to describe what I want to achieve.

As a creator I want to add a new entry, to let users access it through the main page.

I have the idea of adding an entry via Drag&Drop. My company has some guidelines, to have every command always available via context menu and ribbon.

Should I split up my origin story into separate actions?

As a creator I want to drag a new entry onto the main page, to let users access it.

As a creator I want to create a new entry on the main page via ribbon, to let users access it.

As a creator I want to create a new entry on the main page via context menu, to let users access it.

That approach would result in at least three user stories per feature what won't feel comfortable to me.

I could add these expectations during the discussion, but then it seems like giving a "way-to-follow" for developers.

So how would I ensure that the required quality/user experience is achieved?


问:
Which is architecturally correct for Data Access Layer method names - Fetch or Select?
I have seen the words Fetch and Select used seemingly interchangeably when naming data access layer methods (ex. Person.Select or Person.Fetch).   Which one is correct?

My instinct is that the point of the data access layer is to abstract data access and thus the term Fetch would be more of an abstraction perhaps than Select would be.  But if one can imagine for a moment that SQL was not an existing technology, the term Select on its own might be appropriate.

答:
According to the given comments, I'd also say that it's a matter of preference. When I have to cope with naming issues, I usually look for semantic differences of the words in a dictionary.

fetch - go for and then bring back (someone or something) for someone

select - carefully choose as being the best or most suitable

The word select has a notion of choosing between some elements. This is not the case in a Data Access Layer, because in a specific method you know which entity you want to access and thus, the selecting process rather takes place in the Database Layer itself.

Therefore I'd prefer the word fetch in this case, because, according to the definition, you go for an entity's data and you want to bring it back (=forward it) to the next higher layer, maybe the business logics layer.


答:
Unless the performance overhead of using the web service is an issue, you should definitely use your public API.

This will help you get a consistent behavior between your application and the consumers. It will also avoid code duplication and the best part - if you break your web service you will most likely be the first one to notice it.

The concept is usually referred to as "dogfooding" and Twitter is one example of an application, that dogfoods it's own API.

Title: How my website should use its own API?

Body:
Im building small web-service which will provide my users with data through API.
Also, some data will be available right on my website.

The question is about how to use my own API? Should my website make a query to, for example, http://website.com/api/users/?format=json and then render data? Because I can use standard Django ORM features, but this is not corresponding with using of own API.

update:
Imagine that I have a database full of games with release date, game name, game platform etc. And on my own website I will show this games as a list or a grid. Also, this data can be reached through API in JSON format, this data can be updated through API and even deleted. And on my own website I have html forms that allow me to do this actions in a user-friendly way. So how should I access my own API? Via POST request to my API or via django ORM directly to database?


答:
Is this a trend programmers typically follow when going about a project like this?

I suspect what your mentor meant was that you shouldn't build in any additional complexity that may not be required by the final solution.

It is all too easy to think that an app should do this and that and get massively sidetracked.

As for design patterns, it is worth remembering that they're a means to an end. If you find with experience that a certain design pattern doesn't fit despite your earlier hunch, then this could indicate a code smell.

For example, if you were asked to do a proof of concept model, is it a typical trend just to mash a workable example out as soon as possible?

It is worth getting a steer before the project starts as to what milestones there are and whether they'll want to see a bit of everything (vertical slice) or just each part in detail as you develop it (horizontal slice). As part of the initial design, I find it worth story boarding the whole app so even though the code isn't written you can do a helicopter view of the whole thing or a deep dive of a given area.

Title: Over thinking development


答:
1) Is it actually a bad practice?

Yes

Why or why not?

Because of the backward coupling between Timer and Trigger.  By design, Timer does not know anything beyond Timeable.

2) What's a better way if it is a bad practice?

Your requirement isn't exactly clear.  Is the problem to find all triggers for a given target attached to a specific timer, or to find all triggers for a target attached to any timer?  Either way, I have a couple of ideas:

Move "findObjectsWithTarget" out of Timer and into Trigger.  That breaks the    coupling between Timer and Trigger, but may require adding a method to Timer returning all the attached "Timeable" instances.

Record the target -> trigger associations in the Target class.

Title: Is it bad programming practice to check if a class referenced by its interface is an instance of another class?

Body:
I have a class (Timer) with an array list of Timable  objects. Timeable is an interface. There is some specific functionality that I need for the Trigger class (implements Timable), which has a reference called target. A lot of methods need to search through the Timer array for Trigger objects with a certain target.

What I did was a function like this:

```<code>public Timable[] findObjectsWithTarget(Cue target) {
    ArrayList<Timable> result = new ArrayList<Timable>();
    for (Timable timed : fireable) { //fireable is the array (actually a HashSet) of Timed objects
        if (timed instanceof Trigger && ((Trigger) timed).getTarget() == target)
            result.add(timed);
    }
    return (Timable[]) result.toArray();
}
</code>```

This feels like a bad practice. The Timer class is now dependent on the Trigger class (sort of) and are no longer generalized.

So, my two questions:

1) Is it actually a  bad practice? Why or why not?

2) What's a better way if it is a bad practice?


答:
Yes, it's a bad practice, because you're adding functionality to the Timeable interface that you're not specifically declaring, namely the possibility of also being a Trigger.  There are a few different ways to do it better:

Explicitly add the functionality to the Timeable interface, as in woni's answer.  This is better than using instanceof, but still violates the interface segregation principle.

Keep separate lists of Timeable and Trigger objects in the calling code, or at the very least, only keep a combined list in contexts where the Trigger functionality isn't necessary.

Keep a back reference from your target into all the Timeable objects that use it.  In other words, call target.getTriggers() instead of timeableList.findObjectsWithTarget(target).  Often when a method feels awkward, it's because you've put it into the wrong class.  The fact that "a lot of methods" need to do this search means this approach would also have significant time efficiency benefits.


答:
When to choose between Selectand Fetch I would prefer SELECT because it is used in other technologies (SQL, LINQ, ...) and therefore the "what it will do" is more understandable for developers.

Personally I would choose Query, like used in Hibernate or RavenDb, because it implies that you have to do something else than simply selecting a subset of a collection to get the data.

Title: Which is architecturally correct for Data Access Layer method names - Fetch or Select?

Body:
I have seen the words Fetch and Select used seemingly interchangeably when naming data access layer methods (ex. Person.Select or Person.Fetch).   Which one is correct?

My instinct is that the point of the data access layer is to abstract data access and thus the term Fetch would be more of an abstraction perhaps than Select would be.  But if one can imagine for a moment that SQL was not an existing technology, the term Select on its own might be appropriate.


问:
Handling Difficult Distributed Version Control System Merges With Pair Programming
A common problem in my very small team workflow is handling merges from trunk/stable repositories up to feature branches which are ahead of the trunk or stable versions, but which need to track the changes in the trunk and stable versions. We are using mercurial, but any DVCS would perhaps have a similar workflow, including Git, or others.

Originally we had a workflow where a senior developer (me) did most of the merging, as that was the model I had experienced at a previous workplace, but similar to the previous place where we worked like that, this put a lot of burden on one developer to take the results of a large number of commits, and clean up the resulting mess.

If you were merging one change, with one commit message, maybe you could do this cleanly, but what often happens to me, is that I get a little behind, and a week of changes needs to be merged.

What I'm wondering is, when you DO get into a situation where a large merge is necessary, using Mercurial or DVCS,  what is the process that you use, and does it involve collaboration between multiple developers on the team, and does your team use pair programming to solve this complex programming problem of How Do I Sort Out and Land the Changes from TRUNK that need to get to FEATUREXYZ branch.

The workflow or standard-practice I am envisioning looks like this:

when a merge up to a feature branch looks easy and only involves my own changes I do it on my own

when a merge up to a feature branch also pulls in someone else's changes that are not trivial, I involve that person in the merge.

Common sense? I think so.  But I suspect that others have been down this road and can offer a more clearly elaborated, and "tried and true" approach for this general situation.

答:
It somehow sounds going backwards.

The feature branch is owned by one or more people. They know what is it all about. They shall manage its state by whatever means convenient.

The branch will be integrated at some moment, the devs may leave it to the final sate or chose to reduce divergence. In any case it semantically looks like they add their changes to whatever point on trunk.

Ideally the rebase (or merge) just succeeds, the branch compiles, tests work, all happy. If it's not the case, again the branch people will go discovering what happened on main, either just looking at history or grabbing trunk devs for info.  (The good feature of DVCS is the action can be postponed without hindering work...)

Using PP or reviews to look merge impact? if the delta is non-trivial, sure, why not. But if testing framework is in place it's supposed to catch problems in time before final integration.


问:
Refactoring C++
I know that there are some other questions about C++ refactoring, but none satisfies my needs.

I have a background in Java and Python programming, but now I'm approaching C++. I've read (and absolutely love) books about agile coding, test-driven development (TDD), refactoring, etc. The first that comes in my mind is "Clean Code". From this I have learned a lot of things: keep my functions short, keep my classes short, keep names of variables/classes consistent, etc..

I like very much this way of working: first resolve the problem, then refactor in small functions (and one function does only one thing), adding subclasses, etc.

I strongly believe that this way of working is made easy by modern IDEs: add file, rename function, rename classes, etc..

I'm now coding in C++ with CMake inside Qt Creator. All of those things are more difficult. Even adding a file is "more difficult" (I have to generate one header file, one source file, add them to cmakelist.txt, run again cmake, etc.). Thinking about renaming files (I have to manually change all includes) or some strong refactoring methods that in Java with Eclipse has no cost now gives me a headache.

I mean.. it is not "difficult" in the meaning that are "hard task", but the human mind is kind of lazy: if I can do other easiest way..

In Java with some modern IDE like Eclipse.. refactor is the fun part; some clicks and voilà, it is done. I do it every time I pass a test. It is easy, fun, and I like reading my clean code with small functions and nice names.

Now everything is more difficult mainly because there are no tools that can do it without cost. I bare myself in bad attitudes driven by lazyness: write several classes in a single super-long .h file because I don't want to create new files, spent hours in modifying classes/functions/variables with more appropriate names and manually change all includes, write long functions because when I automatically change a function's attributes that concerns the std lib Qt Creator is deleting the templates so I avoid it, and many others..

This is quite frustrating.. What can you advice me? Do I have to get more relaxed in the "rules" of writing clean code? Do I have to does not think about this stuff and thinking only in getting things works? Or (maybe this is the more importart question) do I have to be thinking about some other way of working? No more incremental/iterative/agile way, but more waterfall and spend more time in designing stuff before coding in the hope of minimize the refactoring when the tests are passed?

Anyway, any comment are welcome because I am very far from being a good programmer : )

答:
TL;DR: C++ has an old compilation model and hard-to-process syntax (because it is highly contextual) which makes tools hard to make, but they exists. Refactoring is a bit harder to do in C++, but it's just a bit slower to do than in other languages.

I think you just need some additional information about C++ itself and related tools. Let's see:

There ARE refactoring tools for C++ that would help in renaming files, etc. One example is the Visual Studio plugin Visual Assist X. I think Eclipse and other editors do have some refactoring tools too. They are imperfect, but they have been very useful for me for years. Now, where it is less useful is when you don't organize your code in a way which is usual and "forced" in other languages like Java or Python or C# because...

C++ suffer a lot from using a very old compilation model. It makes some kind of code (header-heavy) slower to compile, it makes hard to locate library headers, etc. The compilation have to be understood to fully understand why depending on the kind of library you use or develop, you will not organize your sources directories the same ways. Anyway, this makes tools hard to build around it. In particular because macros are the way we import modules, which means it's all copy-pasting.

Defining header + source is classic if you are defining most class systems, but it's far from being the normal/only way of doing things in C++. For example, a lot of Boost C++ libraries are header-only which mean there is no associated cpp file and you can't test the code without adding cpp files to compile it (headers don't really exists for the compiler, see the compilation model).

Also, C++ syntax is highly contextual which means a tool that is able to refactor C++ correctly should have the same kind of information about the processed source code as a compiler. That is one reason for the efforts of LLVM to provide libraries to parse and have a correct model of C++ code, which can then be used by tools implementations. However, only a few tools so far are usable, but we expect a lot of refactoring tools to emerge from the LLVM effort in the coming years.

Having a modern, structured and well-defined module system like in Java, C#, Python and Ruby is clearly superior for compilation speed, but more importantly to help the compiler know what is a module and how modules are linked together. The C++ ISO standard committee is working on such a modern module system to be added into the C++17 version if it is ready then. The point is that the issue is acknowledged and being solved. The work on this is being done into the LLVM/Clang compiler.

Beware that CMake is an meta-build-system. What I mean here is that it's independent of the edition tool you use (I use it with Visual Studio for example) and add, indeed, an indirection into the process of adding/removing/renaming file. As C++ don't have any standard build system, it is one such a tool, but it is a meta description of your project. For example, if I directly use Visual Studio or QtCreator default project formats, it is far easier to change file names as you can do it directly into the editor. But indeed these project files are not compatible with other editors/platforms, which is why you use CMake to be sure you will be able to generate project files for a variety of development setups. Basically, if you don't use CMake, refactoring is faster, but you loose cross-editor/cross-platform build-system features.

All that being said, my experience so far with C++ refactoring is that if you have something like VAssistX it is enough to do most of it. Renaming files indeed takes longer to do correctly than in other languages, but it's not that long. That being said, it would be helpful if any change to a C++ project would be faster to check, which is why a module system is really necessary. Hopefully you don't work yet with code that takes an hour or more to compile, in which case the impact on refactoring is devastating as people don't want to modify too much the code, because it's making them insane to have to wait. This is a hard problem for the C++ community and again work is in progress to fix it. But it will take years.

Title: Refactoring C++


答:
There really is no easy way around it.  A fundamental truth about version control is the longer you diverge, the harder the merge. (I should put that on a T-shirt).

There's no reason every team member needs to be involved in the merge every time, but you can rotate it around.  If you can't do it one day, make sure someone else does.  The more your team is involved, the more they will be aware of incompatibilities growing between the branches, and the less likely they will be to make breaking changes.

You should also look for opportunities to merge into the trunk.  You should break long features into intermediate steps that can be safely tested and merged in, even if the entire feature isn't available yet.  New features usually require both rework of old code and creation of brand new code.  It's the former that creates the most merge conflicts.  Luckily, it's also the easiest to change before a feature is complete.

For example, say your new feature requires a certain field of a widely-used existing data structure to be 16 bits instead of 8.  You can usually make a change like that in the trunk without adversely affecting existing code.  The sooner you do so, the sooner the rest of the company will stop making that particular merge conflict in their new code.

In other words, if you're continually fighting the same kinds of merge conflicts, you should look for ways to fix it in the trunk, if at all possible.

Title: Handling Difficult Distributed Version Control System Merges With Pair Programming

Body:
A common problem in my very small team workflow is handling merges from trunk/stable repositories up to feature branches which are ahead of the trunk or stable versions, but which need to track the changes in the trunk and stable versions. We are using mercurial, but any DVCS would perhaps have a similar workflow, including Git, or others.

Originally we had a workflow where a senior developer (me) did most of the merging, as that was the model I had experienced at a previous workplace, but similar to the previous place where we worked like that, this put a lot of burden on one developer to take the results of a large number of commits, and clean up the resulting mess.

If you were merging one change, with one commit message, maybe you could do this cleanly, but what often happens to me, is that I get a little behind, and a week of changes needs to be merged.

What I'm wondering is, when you DO get into a situation where a large merge is necessary, using Mercurial or DVCS,  what is the process that you use, and does it involve collaboration between multiple developers on the team, and does your team use pair programming to solve this complex programming problem of How Do I Sort Out and Land the Changes from TRUNK that need to get to FEATUREXYZ branch.

The workflow or standard-practice I am envisioning looks like this:

when a merge up to a feature branch looks easy and only involves my own changes I do it on my own

when a merge up to a feature branch also pulls in someone else's changes that are not trivial, I involve that person in the merge.

Common sense? I think so.  But I suspect that others have been down this road and can offer a more clearly elaborated, and "tried and true" approach for this general situation.


答: I'd implement something like Target.searchTriggersForTarget(List<Timeable>, Cue) : List<Timeable>.  Target is already dependent on Timeable, so no new coupling there, and you now have your Target-specific logic in the right place.  Just pass in your list of Timeables from Timer and return the result.  This will also facilitate using the same logic in other classes that hold lists of Timeables, which sounds useful since you say it's used in many contexts.


问:
Benefits to using fragments in Android projects
I am learning Android programming and right now and i'm reading about fragments. I understand what fragments are, but either the tutorial is missing some steps or i'm missing something. So my question is when developing an Android UI, what are the benefits, if any, to using fragments as apposed to single page layouts? Are fragments more common than single page layouts or is it more based on the situation. Also, if fragments are more common, do you try to structure most situations so that fragments work?</p>

答:
The benefit is reuse.  You can reuse a fragment in different activities, just like the documentation says.

Imagine an address block on an invoice and a packing list.  The invoice and the packing list are two different activities.  With a fragment, you can write the address block once, and use it in both activities.


问:
Stored Procedures a bad practice at one of worlds largest IT software consulting firms?
I'm working at a project in one of the world's top 3 IT consulting firms, and was told by a DBA that company best practice's state stored procedures are not a "best practice".  This is so contrary to everything I've learned.

Stored procedures give you code reuse, and encapsulation (two pillars of software development), security (you can grant/revoke permissions on an individual stored proc), protect you from SQL injection attacks, and also help with speed (although that DBA said that starting with SQL Server 2008 that even regular SQL queries are compiled if they are run enough times).

We're developing a complex app using Agile software development methodology.  Can anyone think of good reasons why they wouldn't want to use stored procs?  My guess was that the DBAs didn't want to maintain those stored procs, but there seem to be way too many negatives to justify such a design decision.

答:
Programming solo, I cannot resist writing stored procedures.

I'm using MySQL primarily.  I have not used object-oriented databases before like PostGreSQL, but what I'm able to do with SP's in MySQL is abstract the table structure away a little bit.  SP's allow me to design these primitive actions, whose inputs and outputs will not change, even if the database underneath it does change.

So, I have a procedure called logIn.  When you log in, you always just pass username and password.  The result passed back is the integer userId.

When logIn is a stored procedure, now I can add additional work to be done at login that happens at the same time as the initial log in.  I find a series of SQL statements with embedded logic in a stored procedure easier to write than the (calling environment FETCH) -> (get result) -> (calling environment FETCH) series you have to do when you write your logic server side.


问:
Should you reward based on overall project completeness or velocity?
The development team I'm in has been working on a VERY large project for months now and we recently started to implement a kanban board with agile practices into our process. We have seen MASSIVE improvement in our throughput! Its so exciting! But we have one struggle right now. We have a total ticket count for the project and our supervisor has given us incentive(candy and popcorn boxes) for when we get down to 100 and 50 tickets. It at first felt like a great idea but it feels like new tickets are created just as fast as we can resolve them, and its making the team feel worse about our progress. So heres my question:

Should you reward based on overall project completeness or velocity? And if completeness how do you make that feel more reachable?

答:
If you have committed to using a SCRUM methodology - you would have a fixed Sprint Backlog. Its well established that, you should keep the backlog frozen for the duration of the sprint.

If there is an exceptional case for a ticket to give you greater RoI by including it in this sprint after the backlog was frozen - then it makes sense to modify the backlog. However, if you keep adding items to a backlog during the sprint just because the items are being cleared out at a good velocity - it masks the progress and undermines the process.

During the life cycle there would be many tickets created and closed and the number would keep increasing or decreasing during this period.

Count of Tickets solved by themselves dont offer a view of complexity,criticality involved in the issues solved. If you get stuck on two complicated tickets over a 2 week sprint - by the metric of ticket counts closed, you would be pretty badly rated.

Ticket count should not be the metric. Incentive should be given to bug free feature releases in increments. And these increments should be planned for a sprint and the backlog frozen.


答:
One of the major problems when programming traditional languages like C, Java, C#, assembler etc. is that you have an awkward sequence of steps you have to take in order to accomplish a given task because you need to have prepared all the dependencies first and THEIR dependencies earlier

An example:  In order to do A, you must have B and C present, and B depends on D and E, resulting in something like

D

E

C

B

A

because you have to have the ingredients prepared before you can use them.

Functional languages, especially the lazy ones, turn this one upside down.  By letting A say it needs B and C, and let the language runtime figure out when to get B and C (which in turn requires D and E) all of which are evaluated when needed to evaluate A, you can create very small and concise building blocks, which result in small and concise programs.   The lazy languages also allows using infinite lists as only the elements actually used are calculated, and without needing to store the whole datastructure in memory before being able to use it.

The really nice trick, is that this automatic "oh, I need a B and a C" mechanism is scalable because there is no restriction - as in the sequential program - about where and when this evaluation can happen, so it can happen at the same time and even on different processors or computers.

That's why functional languages are interesting - because the "what to do when" mechanism is taken over by the runtime system as opposed to the programmer having to do it manually.  This is as important a difference as the automatic garbage collection was for Java to C, and one of the major reasons why it is easier to write robust, scalable multi-threaded software in Java than in C.  It is even easier to write robust, scalable multi-threaded software in functional languages...

Title: Why the current enthusiasm for Functional Programming?

Body:
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?


问:
Design pattern for maintaining different state(s) across browser tabs in a single session
I have an MVC 4 based web app. Where I provide 2 login types, 1. Employee and 2. Customer.
With Customer login, I present a dashboard and other stuff, about his orders, etc.
With Employee login, I allow the employee to search for his customers and provide the ability to carry out certain customer specific tasks.

It is possible that, an employee after login can seach for a number of customers and fetch each of their details in multiple browser tab(s).

I am having difficulty in maintaining state for each tab, if I put the unique identifier of the customer in session, as the next subsequent request will overwrite the session!

To solve this, I have relied on a (dirty) viewbag based solution, where I set the customer number in viewbag in every view.

Is there an elegant solution to solve this? a known design pattern?

答:
Put the customer identifier in the URL, a la: http://yourApp/Customers/990023 (Custom ID = 990023)

Expanded Answer:

First, register the URL parameter for the Customer ID in your RouteConfig.RegisterRoutes() method (found in RouteConfig.cs). It might look something like this:

```<code>routes.MapRoute(
                name: "Customer",
                url: "Customer/{action}/{id}",
                defaults: new { controller = "Customer", action = "Index", id = UrlParameter.Optional }
            );
</code>```

If every method in the Customer Controller requires the ID, that is, if every action requires that you've got a valid customer loaded, then you can remove the id = UrlParameter.Optional part.

Now, your methods in the Customer Controller will be looking for a URL segment at the end of the URL that maps to a parameter called id. You can access it in your methods like so:

```<code>// GET: /Customer/MakePayment/990023
public ActionResult MakePayment(string id)
{
    var makePayVModel = new MakePaymentViewModel();
    makePayVModel.LoadModelData(memberNumber);
    return View(makePayVModel);
    // or do whatever you want here.....
}
</code>```

Finally, here's a tip. When you are dealing with ActionLinks and the like, say from one customer View to another, make sure you pass in the ID as part of the Route Values. So if your ViewModel for that View has a property called "Id" that represents the Customer Id, you'd make your link might look something like this:

```<code>@Html.ActionLink("Make a Payment", "MakePayment", new { id = Model.Id } )
</code>```

Which would render a tag like so: Make a Payment

Body:
Put the customer identifier in the URL, a la: http://yourApp/Customers/990023 (Custom ID = 990023)

Expanded Answer:

First, register the URL parameter for the Customer ID in your RouteConfig.RegisterRoutes() method (found in RouteConfig.cs). It might look something like this:

routes.MapRoute(
                name: "Customer",
                url: "Customer/{action}/{id}",
                defaults: new { controller = "Customer", action = "Index", id = UrlParameter.Optional }
            );

If every method in the Customer Controller requires the ID, that is, if every action requires that you've got a valid customer loaded, then you can remove the id = UrlParameter.Optional part.

Now, your methods in the Customer Controller will be looking for a URL segment at the end of the URL that maps to a parameter called id. You can access it in your methods like so:

// GET: /Customer/MakePayment/990023
public ActionResult MakePayment(string id)
{
    var makePayVModel = new MakePaymentViewModel();
    makePayVModel.LoadModelData(memberNumber);
    return View(makePayVModel);
    // or do whatever you want here.....
}

Finally, here's a tip. When you are dealing with ActionLinks and the like, say from one customer View to another, make sure you pass in the ID as part of the Route Values. So if your ViewModel for that View has a property called "Id" that represents the Customer Id, you'd make your link might look something like this:

@Html.ActionLink("Make a Payment", "MakePayment", new { id = Model.Id } )

Which would render a tag like so: <a href="http://yourApp/Customer/MakePayment/990023">Make a Payment</a>


问:
Experience w/ eLance (and similar sites)
I'm considering freelancing via eLance.com (or another similar site) to help pay the bills while developing games (that will eventually pay the bills).  What's working through elance like?  Any recommendations or strategies?  Any feedback is appreciated.

答:
I have worked on couple of projects through Elance. Of all the similar sites I found Elance much more sophisticated and professional. While on Elance I follow the following guidelines while posting. (I have learned through my experience on Elance and drew these lines).

When you post a proposal for any project make sure you have also posted the Software Requirements Specification (SRS) and have defined who will be responsible to satisfy the required SRS. I had to cancel my first project due to these difference. I needed Java and Tomcat installed on server and the party wasn't ready to do it for reasons best known to them.

When you post any proposal don't give away every details of development. Not all but there are few highly creative souls on Elance they might use your guidelines and even ask you for a demo. Later they would use the same to implement the project without paying you. So in such a condition either ask for some money and say that it would be deducted from the final payable if project is assigned else would be non refundable, or if possible give the demo through your resources like if you have a VPS server or a PHP reseller A/C. Be agile in handing over your source code.

Be patient to get the response on proposals you have submitted it is a time consuming process to earn on Elance.

Prefer posting proposal for projects/job post which are about to expire. This is because if some one has just posted a job and the validity is of 30 days(ex) then they will get into finalization after 30 days only which would again take 2 weeks to complete. So post on projects about to finish to get relatively quicker response.

Carefully go through the posting and make sure you can deliver exactly what the client is looking for. If you have a different suggestion like they need Dojo Java scripting and you work with jQuery then try to convince them to use jQuery instead but if they don't agree then unless you are sure don't post. Because on Elance people just don't want the things to be done, they want them to do be done in the way that they need them to be. So even if with jQuery you can deliver him the same end result it is not necessarily what they are looking for.


问:
Same constructor signature with different semantics?
Occasionally, I'm confronted with the problem that I have to provide some constructors in order to initialize objects with different sets of data. These sets can be mathematically transformed into each other, for example:

```<code>        public Element(int x, int y, int width, int height)
        {
            setValues(width, height, x, y);
        }

        public Element(int RectTop, int RectLeft, int RectRight, int RectBottom)
        {
            setValues(RectRight - RectLeft, Math.Abs(RectBottom - RectTop), RectLeft, -RectTop);
        }
</code>```

With such an desired overloading, which actually isn't any because of the same signatures, it is probable that the wrong constructor is invoked, e.g. you provide the Rect-Values and the first constructor is invoked. Assuming, we would have different types, we could achieve it by swapping types with good knowledge that this is a bad practice. But that's simply not the case in this easy example with four times int type.

Can you think of some elegant alternatives to achieve the desired behavior that we have the convenience of overloading, but with the same signature?

答:
One way to do it would be to write a constructor that accepts a Rectangle object.

```<code>public Element(Rectangle r) { ...
</code>```

Which you can then call thusly:

```<code>var element = new Element(new Rectangle(x, y, width, height));
</code>```

Of course, now you're back where you started, since Rectangle asks for the very same parameters that your first overload does.

If you're committed to providing a constructor overload for the slight variation in math, you could simply add a boolean flag to make the signature unique.  Something like:

```<code>public Element(int RectTop, int RectLeft, int RectRight, int RectBottom, bool isRect)
</code>```

It's a bit of a hack, and it doesn't matter what you pass in to the bool parameter, but it does guarantee that particular overload will be called.

Body:
One way to do it would be to write a constructor that accepts a Rectangle object.

public Element(Rectangle r) { ...

Which you can then call thusly:

var element = new Element(new Rectangle(x, y, width, height));

Of course, now you're back where you started, since Rectangle asks for the very same parameters that your first overload does.

If you're committed to providing a constructor overload for the slight variation in math, you could simply add a boolean flag to make the signature unique.  Something like:

public Element(int RectTop, int RectLeft, int RectRight, int RectBottom, bool isRect)

It's a bit of a hack, and it doesn't matter what you pass in to the bool parameter, but it does guarantee that particular overload will be called.


问:
View is calling constructor method in the Model instead of passing model to the controller method
The problem is the UserTypes property (used to populate a drop down list in the AddUser view) is not being retained after POSTback of the form.

Here is my AddUserModel: (which inherits from EditUserModel which doesn't have properties for UserTypes/UserTypesSelectList - probably part of the problem?)

```<code> public class AddUserModel : EditUserModel
    {
        public AddUserModel() : this(new Dictionary<string, string>())
        {
        }

        public AddUserModel(Dictionary<string,string> userTypes)
        {
            UserTypes= userTypes;
        }

        //properties etc

        public Dictionary<string, string> UserTypes{ get; private set; }

        public SelectList UserTypesList
        {
            get { return new SelectList(UserTypes, "key", "value"); }
        }
}
</code>```

The view has the following but it calls the parameterless constructor in the above code first instead of the AddUser() method in the controller:

```<code>   using (Html.BeginForm<MyController>(c => c.AddUser(Model)
</code>```

I can see when debugging that this is because the parameterless constructor method in the AddUserModel is being called first instead of the controller method being called (thereby instantiating an empty AddUserModel). I found this question on this site but I still do not understand.

Debugging shows that after POSTback of the form the AddUserModel contains no data, but the EditUserModel does contain the data (except the UserTypes data because it doesn't have a property for that)

Should both the Add and Edit Models have the same properties? i.e UserTypes and UserTypesSelectList? Is there something I'm missing in terms of how Models inherit from each other and relate to Views?

Edit

After abit of research and deciding to use a shared model I was able to fix the above. Please refer to my answer for more details.

答: I solved this problem by making a shared model for both AddUser and EditUser rather than having two separate models with AddUserModel inheriting from EditUserModel. When submitting the form in the view the default/parameterless constructor is always called and that is the expected behaviour of MVC and not an error as I first suspected.</p>


答:
```<code>public Element(Point topLeft, Size size)

public Element(Point topLeft, Point bottomRight)
</code>```

You could also use factory methods

```<code>public static Element FromLeftTopWidthSize(int left, int top, int width, int height)

public static Element FromLeftTopRightBottom(int left, int top, int right, int bottom)
</code>```

Or you can use a fluent interface

```<code>Element.Top(10).Left(28).Right(112).Bottom(101);

Element.Top(10).Left(28).Width(102).Height(73);
</code>```

You can easily use interfaces to force Left after Top, Right or Width after Left, Bottom after Right, and Height after Width. (see below)

Or, you can do the most sensible thing of all and not allow the different choices. Just choose one and stick to it.

Example of a Progressive Fluent Interface:

```<code>public class ElementBuilder : ITopSyntax, ILeftSyntax, IRightSyntax, IWidthSyntax
{
    private int _top;
    private int _left;
    private int _right;

    public ElementBuilder(int top)
    {
        _top = top;
    }

    ILeftSyntax ITopSyntax.Left(int left)
    {
        _left = left;
        return this;
    }

    IRightSyntax ILeftSyntax.Right(int right)
    {
        _right = right;
        return this;
    }

    IWidthSyntax ILeftSyntax.Width(int width)
    {
        _right = width + _left;
        return this;
    }

    Element IRightSyntax.Bottom(int bottom)
    {
        return new Element(_left, _top, _right, bottom);
    }

    Element IWidthSyntax.Height(int height)
    {
        return new Element(_left, _top, _right, _top + height);
    }
}

internal interface ILeftSyntax
{
    IRightSyntax Right(int right);
    IWidthSyntax Width(int width);
}

internal interface IRightSyntax
{
    Element Bottom(int bottom);
}

internal interface IWidthSyntax
{
    Element Height(int height);
}

internal interface ITopSyntax
{
    ILeftSyntax Left(int left);
}
</code>```

Title: Same constructor signature with different semantics?

Body:
Occasionally, I'm confronted with the problem that I have to provide some constructors in order to initialize objects with different sets of data. These sets can be mathematically transformed into each other, for example:

```<code>        public Element(int x, int y, int width, int height)
        {
            setValues(width, height, x, y);
        }

        public Element(int RectTop, int RectLeft, int RectRight, int RectBottom)
        {
            setValues(RectRight - RectLeft, Math.Abs(RectBottom - RectTop), RectLeft, -RectTop);
        }
</code>```

With such an desired overloading, which actually isn't any because of the same signatures, it is probable that the wrong constructor is invoked, e.g. you provide the Rect-Values and the first constructor is invoked. Assuming, we would have different types, we could achieve it by swapping types with good knowledge that this is a bad practice. But that's simply not the case in this easy example with four times int type.

Can you think of some elegant alternatives to achieve the desired behavior that we have the convenience of overloading, but with the same signature?

Body:
public Element(Point topLeft, Size size)

public Element(Point topLeft, Point bottomRight)

You could also use factory methods

public static Element FromLeftTopWidthSize(int left, int top, int width, int height)

public static Element FromLeftTopRightBottom(int left, int top, int right, int bottom)

Or you can use a fluent interface

Element.Top(10).Left(28).Right(112).Bottom(101);

Element.Top(10).Left(28).Width(102).Height(73);

You can easily use interfaces to force Left after Top, Right or Width after Left, Bottom after Right, and Height after Width. (see below)

Or, you can do the most sensible thing of all and not allow the different choices. Just choose one and stick to it.

Example of a Progressive Fluent Interface:

public class ElementBuilder : ITopSyntax, ILeftSyntax, IRightSyntax, IWidthSyntax
{
    private int _top;
    private int _left;
    private int _right;

    public ElementBuilder(int top)
    {
        _top = top;
    }

    ILeftSyntax ITopSyntax.Left(int left)
    {
        _left = left;
        return this;
    }

    IRightSyntax ILeftSyntax.Right(int right)
    {
        _right = right;
        return this;
    }

    IWidthSyntax ILeftSyntax.Width(int width)
    {
        _right = width + _left;
        return this;
    }

    Element IRightSyntax.Bottom(int bottom)
    {
        return new Element(_left, _top, _right, bottom);
    }

    Element IWidthSyntax.Height(int height)
    {
        return new Element(_left, _top, _right, _top + height);
    }
}

internal interface ILeftSyntax
{
    IRightSyntax Right(int right);
    IWidthSyntax Width(int width);
}

internal interface IRightSyntax
{
    Element Bottom(int bottom);
}

internal interface IWidthSyntax
{
    Element Height(int height);
}

internal interface ITopSyntax
{
    ILeftSyntax Left(int left);
}


答:
Fragments aren't terribly useful on a phone.  They were added to the API when people started wanting easier ways to take advantage of the extra real estate on a tablet.

Think of an app with a list down the left side.  When you select an item on the list, it launches a new activity using the remainder of the screen space, and you want to be able to swipe to cycle between previously selected activities.

Without fragments, you require a class to manage the entire screen, keep a stack of which activities have been selected, keep track of which one is current, and manage all of their life cycles.  If you use the same app on a phone, where the activity takes the entire screen, you don't need the manager class.  With fragments, all the life cycle stuff is handled for you, essentially moving your manager class into the operating system.  That makes tablet development easier and more standardized, and also makes sharing code between phones and tablets easier.

Title: Benefits to using fragments in Android projects

Body: I am learning Android programming and right now and i'm reading about fragments. I understand what fragments are, but either the tutorial is missing some steps or i'm missing something. So my question is when developing an Android UI, what are the benefits, if any, to using fragments as apposed to single page layouts? Are fragments more common than single page layouts or is it more based on the situation. Also, if fragments are more common, do you try to structure most situations so that fragments work?</p>


答:
Agile developers have a saying, "You Aren't Gonna Need it (YAGNI)" which encourages that you design for what you need now rather than what you think you might need in the future. To extend a design to work in the future, the recommended route is to refactor.

The important aspect to this is to keep the requirements for your product in your mind as you design, and to ensure that you are not designing for a bunch of requirements that might happen in the future.

There is something to be said for developers who can think two or three iterations ahead - they know their clients or the domain so well that they can anticipate future needs with high degrees of accuracy and build for them, but if you're not sure, it's best not to spend too much time on things that you or the clients don't need.

Title: Over thinking development


问:
Does dedicated maintenance work hamper a programmer's career?
The majority of my work over the last three years has largely been around maintaining legacy systems that needed patching up or the occasional revamp before being sold again.

I understand the critical role dedicated maintenance programmers have to play in companies with a large number of projects and limited developers on hand.

But as I judge my current career progress and look at my peers; contractors and corporate developers alike; I do feel as if I am lagging far behind since I've gained a great deal of breadth in terms of the areas I've touched but not much depth.
I've begun to address this by starting a blog, working on my own little git-hub projects and rescheduling my life to have time to do personal coding after work on a regular basis.

I feel that were I to interview at other companies to escape maintenance work I would have to represent myself as being quite junior in skill level since I would not have the depth of level of knowledge required of a person with three years experience focused on a particular path in feature development would. So half my current work experience would count for naught in the long run.

But this leads me to my main questions, apologies if this feels too centered around my personal dilemma,:

Do dedicated maintenance programming roles end up being detrimental to an early career?
Are other programmers right to avoid roles like these?
Does doing this line of work lock you into doing similar tasks unless you're prepared to start over as a junior?

答:
Looking at this from a different angle, I think selling yourself as an expert in maintenance is a marketable opportunity.

As an owner of a software company that has multiple projects on the go, one of the biggest risks I have to minimise is developers who jump ship, and the subsequent maintenance of their code.

So assuming you're capable of growing passionate about maintenance work (which I would guess to be the case since you're prepared to blog about your experience), if you came to me offering your services as a maintenance guru - guaranteeing to polish all of my developers' various projects by refactoring, optimising and documenting their code for long-term maintainability - and you had a track record to back up your guarantee, I'd hire you in a flash.

My advice would be to give this a proper try. Position yourself as a maintenance expert and cultivate your blog. You may be on to something.


答:
Captain Obvious to the Rescue!

I'll be Captain Obvious here and say that there's some middle ground to be found.

You do want to build for the future and avoid locking yourself into a technological choice or a bad design. But you don't want to spend 3 months designing something that should be simple, or adding extension points for a quick and dirty app that will have a 2 year lifespan and is unlikely to have follow-up projects.

It's difficult to find the distinction, because you can't always predict the success of your product and if you'll need to extend it later.

Build for Now if...

the project is going to get scrapped

the project has a short life-span

the project should not have extensions

the project doesn't have a risk impact value (mostly in terms of image)

In general, in-house projects or something built for a customer should be developed for now. Be sure to have straight requirements, and relate to them as needed to know what's needed and what's not. Don't want to spend too much time on anything that's "nice to have." But don't code like a pig either.

Leave the General Problem for later, if it may ever be necessary and worth the effort:

Build for the Future if...

the project will be public

the project is a component to be reused

the project is a stepping stone for other projects

the project will have follow-up projects or service releases with enhancements

If you're building for something public, or that's going to be reused in other projects, then you've got a much higher probability that a bad design will come back to haunt you, so you should pay more attention to that. But it's not always guaranteed.

Guidelines

I'd say adhere to the following principles as best as you can, and you should put yourself in the position of designing efficient, adaptable products:

know that YAGNI,

KISS,

whenever you feel like scratching an itch and think of an addition, write it down. Look back at your project requirements and ask yourself if additions are priorities or not. Ask if they add primary business value or not.

I know that I personally tend to overthink and overengineer. It really helps to write ideas down and very often re-think if I need additional features. Often, the answer is no, or, "it would be cool later." Those last ideas are dangerous, because they stay in the back of my head, and I need to force myself not to plan for them.

The best way to code without overengineering and without blocking yourself for later is to focus on a good minimal design. Break things down nicely as components that you can later extend, but without thinking already about how they may be extended later. You can't predict the future.

Just build simple things.

Dilemmata

Overengineering

Is this a trend programmers typically follow when going about a project like this?

Hell yeah. It's a known dilemma, and it only shows that you care about the product. If you don't, that's more worrying. There is disagreement about whether or not less is always truly more and if worse is always truly better. You may be a MIT or New Jersey kind of guy. There is no easy answer here.

Prototyping / Quick-n-Dirty / Less is More

Is it a typical trend just to mash a workable example out as soon as possible?

It's a prevalent practice, but it's not how the vast majority of projects are approached. Still, prototyping is a good trend in my opinion, but one with a mean downside. It can be tempting to promote quick and dirty prototypes to actual products, or to use them as the base for actual products under management pressure or time constraints. That's when prototyping can come back to haunt you.

There are obvious advantages to prototyping, but also a lot of potential for misuse and abuse (many the exact inverse of the previously listed advantages as an outcome).

When to Use Prototyping?

There are hints as to the best types of projects to use prototyping:

[...] prototyping is most beneficial in systems that will have many interactions with the users.

[...] prototyping is very effective in the analysis and design of on-line systems, especially for transaction processing, where the use of screen dialogs is much more in evidence. The greater the interaction between the computer and the user, the greater the benefit [...]

"One of the most productive uses of rapid prototyping to date has been as a tool for iterative user requirements engineering and human-computer interface design."

On the other hand:

Systems with little user interaction, such as batch processing or systems that mostly do calculations, benefit little from prototyping. Sometimes, the coding needed to perform the system functions may be too intensive and the potential gains that prototyping could provide are too small.

And if you have a green monster around, just make sure to keep a prototype within budget...

Title: Over thinking development


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
I agree with FarmBoy.

People that only know HTML/PHP can start a business and earn a fair amount of money.

I also agree with Quickly_now, although .NET is not something that will easily become old..


问:
Database Design - Optimise Relationships
I am about to embark on a redesign of an application, one where querying the database is particularly annoying. I intend to redesign the database as much as possible but the data shape cannot change too much.

The  database has a main table and 10 other tables each representing a record type. The main table has all of the data the record types have in common. Record ID, DateLogged etc. Around 30-40 columns in total.  The other tables are all completely different as each record type is very different from another. They all have about 20-30 columns each.

The main table has a column called type, which is an int. However nowhere does it reference what record types the type numbers refer to. You can just figure it our by looking at the procedures. The main table has to join with each type table to allow searching. I have added an image representing what I am trying to describe.

Is there a better way to create these relationships? I would like to ditch the verbose stored procs used with ADO.NET and move to EF. I need to think of a better way to relating the data so people in the future wont need to work out the relationships by scouring stored procedures for clues.

答:
Add a Type table.

```<code>TypeID     PK
Type       string
</code>```

Change Type in Main to TypeID, making it a Foreign Key to the Type table TypeID.

Where you go from here depends on how distinct each type is.  If the only distinction is that the fields vary somewhat between types, and there are only a few types, you might get away with having a single Types table, adding a TypeID to it, and putting every field for every type in each record (with the understanding that some fields are going to be empty for every record).

If the types are very distinct, you can keep your current design, but add TypeID to each of the Type tables.

Body:
Add a Type table.

TypeID     PK
Type       string

Change Type in Main to TypeID, making it a Foreign Key to the Type table TypeID.

Where you go from here depends on how distinct each type is.  If the only distinction is that the fields vary somewhat between types, and there are only a few types, you might get away with having a single Types table, adding a TypeID to it, and putting every field for every type in each record (with the understanding that some fields are going to be empty for every record).

If the types are very distinct, you can keep your current design, but add TypeID to each of the Type tables.


问:
Do coding puzzles make good interview questions
I am interviewing candidates for Java programmer positions.

My colleague insists in filling more than half of the interview with java coding puzzles.His view is that, if candidates are able to navigate through the loops, then they must be good.

One such example of coding puzzle is

```<code>        i=0;
        for( i=1 ; i< 10 ;i++)
        {
                if(i%3 ==0) i++; break;
                if(i%2 ==0) i++;

         }
          print(i);
</code>```

Follow up: what happens if break is removed ?

答:
These puzzles are simply a proxy to measure your IQ, or at least your logical reasoning skills. The obvious rationale is that, in the long run, a clever person will learn whatever technology stack they are using, whereas nobody can increase their intelligence. Does intelligence has a strong positive correlation with being a good programmer. I suspect so, however there are many more variables and experience cannot be brushed off so readily.

I think using puzzles is not a bad method, possibly a combination of puzzles and actual coding would be best.

In my opinion, the worst method is face to face interviews since you are seeing that person and you cannot help jumping to conclussions in just 30 minutes based on spurious assumptions (whether the candidate is fat, stutters or speaks slowly or, conversely, is very articulate). Even if you are aware of this, you will still unconsciously discriminate based on arbitrary variables.