问:
Should I place functions that are only used in one other function, within that function?
Specifically, I'm writing in JavaScript.

Let's say my primary function is Function A. If Function A makes several calls to Function B, but Function B is not used anywhere else, then should I just place Function B within Function A?

Is that good practice? Or should I still put Function B at the same scope as Function A?

答:
You should put it at global scope, for several reasons.

Nesting a helper function into the caller increases the length of the caller. Function length is almost always a negative indicator; short functions are easier to understand, to memorize, to debug and to maintain.

If the helper function has a sensible name, reading that name is enough without needing to see the definition nearby. If you do need to see the helper definition in order to understand the caller function, then that caller is doing too much, or is working on too many levels of abstraction simultaneously.

Having the helper globally available allows other functions to call it if it turns it to be generally useful after all. If the helper isn't available, you're tempted to cut and paste it, or to forget it and reimplement it, poorly, or to make another function longer than it has to be.

Nesting the helper function increases the temptation to use variables from the caller's scope without declaration, so that it becomes unclear what the inputs and outputs of the helper are. If a function doesn't clearly state what data it operates on and what effects it has, it is usually a sign of unclear responsibilities. Declaring the helper ass a standalone function forces you to know just what it actually does.

Edit

That turned out to be a more controversial question than I thought. To clarify:

In JavaScript, big file-spanning functions often fulfill the role of classes because the language doesn't provide any other scope-limiting mechanism. Certainly helper functions should go inside such quasi-classes, not outside them.

And the point about easier reuse presupposes that if a subroutine does become more widely used, you are willing to move it out of place altogether and put it in appropriate place, e.g. a string utility library or into your global configuration registry. If you don't want to order your code like that, then you might as well nest the subroutine, just like you would do with a normal Method Object in a more "blocky" language.


问:
JavaScript Compression and Caching of Assets
I'm working on an idea that i can't seem to find a good answer though hours and hours of searching,

I'm planning a small Canvas/WebGL Application this application will be using WebSockets to talk to a game server for syncing data to and from so think of it as a MMO type service

so im planning to have a queuing system to load assets
E.G
I make a request to get model1 and it's texture so that will quee

```<code>Mthd | Data                   | q | p | s
GET  | /asset/model_1/model   | 0 | 0 | 0
GET  | /asset/model_1/texture | 0 | 0 | 0
GET  | /asset/model_1/model   | 1 | 1 | 0
GET  | /asset/model_1/texture | 1 | 1 | 0
...
GET  | /asset/model_1/model   | 5 | 5 | 0
GET  | /asset/model_1/texture | 5 | 5 | 0
</code>```

Key

```<code>q = quality modifier
p = priority lower is better
s = status `0 not started, 1 downloading, 2 complete`
</code>```

so my client is processing that download que however while this is going on another player has come into my view so i need that players model and texture so i add them to the que and end up like so

```<code>Mthd | Data                   | q | p | s
GET  | /asset/model_1/model   | 0 | 0 | 2
GET  | /asset/model_1/texture | 0 | 0 | 2
GET  | /asset/model_2/model   | 0 | 0 | 0
GET  | /asset/model_2/texture | 0 | 0 | 0
GET  | /asset/model_1/model   | 1 | 1 | 1
GET  | /asset/model_1/texture | 1 | 1 | 0
GET  | /asset/model_2/model   | 1 | 1 | 0
GET  | /asset/model_2/texture | 1 | 1 | 0
...
GET  | /asset/model_1/model   | 5 | 5 | 0
GET  | /asset/model_1/texture | 5 | 5 | 0
GET  | /asset/model_2/model   | 5 | 5 | 0
GET  | /asset/model_2/texture | 5 | 5 | 0
</code>```

Now i'm wanting to cache these file into the browser cache so i'm tied between using the database and compressing using something like LWZ, or putting the assets online and using appCache and loading them.

So My Questions.

If i load an asset though the browser normally (http request) will the browser will keep that image in memory once it's no longer being rendered.

If i use Javascript to hold the base64 string should i then remove the string from the javascript variable (delete) i know it would free up the memory holding the string but would it free it all the memory used or would the browser still keep a copy of the image generated from base64 in memory.

Is it possible to write content loading through WebSockets into the appCache E.G the base64 string from the WebSocket Server.

Has any one found a better string compression system for Javascript other than LWZ i'm planning on compressing using a application at the server side so the only limit on compression is javascript supporting it.

答:
If i load an asset though the browser normally (http request) will the
  browser will keep that image in memory once it's no longer being
  rendered.

Browser typically cache files, like images. When asking the server for files it first asks if they have changed. If the browser returns that the file has not changed the browser will use the file from cache. (This has caused a few interesting issues when making changes to .css and .js files where the new file is not pushed out to the client). For an experament I was able to delete an image from a web page after it had loaded (using the Dev Tools for both Firefox and Chrome) and then copy back in the HTML to render the image. Looking at the network history for the page it shows the initial load of the image but not a second request after loading the HTML back into the page.

If i use Javascript to hold the base64 string should i then remove the
  string from the javascript variable (delete) i know it would free up
  the memory holding the string but would it free it all the memory used
  or would the browser still keep a copy of the image generated from
  base64 in memory.

If you make a call to change the image from a base64 encoded string back into an image the image should then not require the string to exist. Overall you should also not have to delete a javascript variable as the garbage collector should take care of it after it is not being used.

Is it possible to write content loading through WebSockets into the
  appCache E.G the base64 string from the WebSocket Server.

From my experience with websockets (jWebsockets to be precise) they interface with the loaded javascript on the page. Because you can also use javascript to write to the appCache you should have no problem writing your base64 string to the appCache.

http://www.html5rocks.com/en/tutorials/appcache/beginner/

Has any one found a better string compression system for Javascript
  other than LWZ i'm planning on compressing using a application at the
  server side so the only limit on compression is javascript supporting
  it.

Sorry can't help with this one. Seems this is the most popular option. Without running a lot of benchmarks I could not give you a reason to use an alternative.

ContentLicense: CC BY-SA 3.0


问:
Architecture for dashboard
I'd like to know if my Architecture idea, is the best approach following some pattern.

I'll create a Dashboard for my company, and I never will delete or update data in my database, just read the data from database.

Nowadays we just work with our SQL Server database, but I want a solution that will provide a easy way to implement a new feature, like a new database compatibility.

THE APPLICATION

This is a dashboard for all my clients, where I'll get the data from my database server making a filter for his company, and then plot some charts and show informations about her rentability, financial information, etc.

Will be web-based and must work in any screen size (smarthphones, TV's, desktop, etc).

I want to use NHibernate as ORM

IDEA

My idea was in the user interface, use MVC 4 Web Application and all request from the User Interface to my Business Layer will be through REST.

My Business Layer it's a MVC Web API, to desacouple the User Interface from my Business Layer.

The Business Layer will access Repository (Repository Pattern), with CRUD operation (in my case it's just 'SELECTS' because I just need show the data, never update, never insert).

It's a DDD approach, working with NHibernate.

Sometimes I think it's to much for a dashboard, where we can't insert nor update data.

I'd like to know what are common architectural pattern for this problem.

I said some pattern's here, but maybe someone with more experience then me could see a better approach to this kind of application.

答:
User Interface

The requirement for working on a range of devices from smart phones to desktops is addressed by two different approaches:

Recognize the type of device and produce a different site page for phones versus desktops. This often yields funny results on large tablets. Not funny in the good sense.

Use strong dynamic layout with cascading style sheets to position items on the page based on screen size and resolution. This yields very usable, scalable sites. They also work quite well when users want to rescale the browser page on a desktop. Here is a good discussion.

The dynamic layout approach then suggests that you organize your dashboard into a set of UI widgets. Each widget would have a set of graphical elements, fixed textual elements, dynamic text and dynamic graphical elements. The widget is then tied together with scripts that properly display the widget as well as querying the back end for data.

Client Back End

As you have already identified, your server back end would be accessed by REST requests initiated by individual widgets. Each REST request would be essentially stateless. That is not to say that you wouldn't store your client profiles and user profiles in such a way that you couldn't always determine that any particular web application can only see exactly what it should see.

Each widget needs to periodically get updated data from the server. It will poll the server using a REST request passing the parameters configured into it as well as a session ID used to authorize access to that data.

Title: Architecture for dashboard


问:
I have generally read that having many (>4) arguments to a function/constructor is a bad practice. Is this still considered a bad practice?
I have generally read that having many (>4) arguments to a function/constructor is a bad practice.

Is this still considered a bad practice? And is there a non-obvious reason?

In something like a Scala Case Class where there may be many fields what can be done to avoid such a construction?

(Not sure if this is best fit for here, SO, or CodeReview)

答:
I have several 'smell' tests for 'best practice'. Some come about through bad implementations, or weak tools. Some help our imperfect minds to create high quality stuff. Some are identified by correlations between code and bugs (though causality might never be demonstrated). So I like to understand what a rule is contributing.

It is pretty clear that lots of parameters can become a usability challenge.

However, lets test against some stiffer criteria.

Lots of systems do CRUD transactions on relational databases.

So, one test is "would this 'best practice rule' effect my codes CRUD transactions in a positive or negative way?"

After all, though you might not like my benchmark, relational databases are intended to represent chunks of the real world in robust, ACID transactional ways.

Building incomplete relationships, that don't represent real-world state, is usually "a bad thing". It creates extra complexity to support it, with no apparent pay-off.

This isn't a license to ignore "proper types". If parts of the constructor or function parameter list contains the values of real meaningful types, representing something relevant in the domain, that has behaviour in the application, then those should be constructed or passed.

AFAIK, all functional languages explicitly provide mechanisms to represent and build 'proper relationships', and that is 'a good thing'.

So I accept that there are some simple, reasonable usability issues, which shouldn't be ignored.

However, in the case of a functional language '>4' does not seem helpful.
Immutability is a much bigger 'hammer' to crack problems.
For me, correctly representing the state of reality, trumps '>4' every time.


问:
docker-izing a classical db-based webapp - single or multiple containers?
I have a classic Java webapp.  It is composed of a database (PostgreSQL), a servlet container (Tomcat) and my code (deployed on Tomcat as a *.war file).

I want to package/deploy it using Docker (mostly for testing for now), but I'm unsure what would be the best way to "map" it.

My initial idea was to have an app-in-a-box - define a container that has Java, Postgres and Tomcat on it, exposing just the http port.

Further reading of the Docker docs shows that this, although possible (install and run supervisord as the single foreground process, have it start both Postgres and Tomcat) is probably not the intended usage.  Going by the spirit of the tutorials I should probably create a container for Postgres, another for Tomcat, and a data-container to hold the application code (my *.war) and database files.  This would mean 3+ containers (should the db files and *.war share the same data container?)

What's the common practice here?

Since I have no previous experience with Docker, what pitfalls can I expect from each approach?

Is there some other approach I'm missing?

答:
The recommendations I've seen is to have all-in-one container: Docker Misconceptions:

Misconception: You should have only one process per Docker container!

It's important to understand that it is far simpler to manage Docker
  if you view it as role-based virtual machine rather than as deployable
  single-purpose processes. For example, you'd build an 'app' container
  that is very similar to an 'app' VM you'd create along with the init,
  cron, ssh, etc processes within it. Don't try to capture every process
  in its own container with a separate container for ssh, cron, app, web
  server, etc.

One way to think about it is to ask yourself if you'd ever need one piece running without the others. OK, maybe you'd want the DB running without the app server, but how often?


问:
Is it considered bad practice to make a DAO call in an object's constructor?
I am trying to figure out the best design for instantiating an object which requires two separate calls to the data layer through a DAO. The object is not usable until these calls have been made (because it requires the data retrieved from the database). I have come up with three possible solutions:

Create a method in the DAO itself that gets the necessary data from the database, and then pass the data to the object's constructor. The object is passed back as the return value.

Create a method in the class that is using the object. This method would make both calls to public methods in the DAO, then instantiate and return the object as in step 1.

Pass the DAO as a parameter to the constructor of the object. The constructor would then make both necessary calls to the DAO, setting its own member variables without the need for Setters. The DAO is not used other than in the constructor.

Examples, if SomeObject is the object I want to create, and Foo is the class that will make use of it:

1 - DAO Contains the logic:

```<code>public SomeObject getSomeObject(){ // this DAO method called by Foo class
     data1 = getData1();
     data2 = getData2();
     return new SomeObject(data1,data2);
}
</code>```

2 - Class that uses object contains the logic:

```<code>public class Foo {
    ...
         public void useSomeObject() {
              SomeObject obj = createSomeObject();
              obj.doStuff();
         }

         private SomeObject createSomeObject() {
              data1 = dao.getData1();
              data2 = dao.getData2();
              SomeObject someObject = new SomeObject(data1,data2);
              return someObject;
         }
}
</code>```

3 - SomeObject takes DAO as parameter and uses it in constructor:

```<code>public class SomeObject {
...
      public SomeObject(DAO dao) {
           data1 = dao.getData1();
           data2 = dao.getData2();
      }
...
 }
</code>```

Hopefully these examples are sufficient to convey my point. Are any of these solution considered better design than the others? If not, what solution is considered best practice?

Thanks.

答:
I would go with your third option. It allows you to pass whatever DAO you want, and that could be very useful for testing. It also makes your code a bit more flexible: in case the details of data retrieval change, you only have modify the DAO class, and SomeObject should work more or less the same.

The first option isn't that bad. The data retrieval methods are within SomeObject so now your class is a business object and a DAO.

The second option could lead to a situation where createSomeObject gets copied and pasted around, as the need to create a SomeObject increases and spreads throughout your application (I know, it might not happen, but it might). And when that happens, you'll wish you had the data retrieval code in a central place, such as the constructor for SomeObject, which is where you started.


问:
Interactive session with a command line program using Java?
I plan to write a website frontend for a free computer algebra system (Reduce, http://reduce-algebra.com/). On the webserver I have a Java virtual machine running, and Reduce is also installed.

I can start the application via exec() in the Java file. But my question is the following: how can I emulate user inputs and how can I retrieve the outputs of the program? The main issue is that I want to log the whole session, not just call the program once, get the output, close it, and restart it again.

I need a way that allows for interactive communication, i.e. a way to "paste" a command in the command line, and a way to "copy" the response back to the Java program.

答: System.exec() returns a Process object, and that object allows you to get access to STDIN and STDOUT of the forked process. The names MAY seem backwards, though -- the child's STDIN is acquired via getOutputStream() -- but the names are from the point of view of your process, not the child.</p>


问:
Why doesn't Python allow multi-line lambdas?
Can someone explain the concrete reasons why BDFL choose to make Python lambdas single line?

This is good:

```<code>lambda x: x**x
</code>```

This results in an error:

```<code>lambda x:
    x**x
</code>```

I understand that making lambda multi-line would somehow "disturb" the normal indentation rules and would require adding more exceptions, but isn't that worth the benefits?

Look at JavaScript, for example. How can one live without those anonymous functions? They're indispensable. Don't Pythonistas want to get rid of having to name every multi-line function just to pass it as an argument?

答:
Hacking together a multi-statement lambda isn't quite as bad as pyrospade makes out: sure we could compose a bunch of monadic functions using bind, like in Haskell, but since we're in the impure world of Python, we might as well use side-effects to achieve the same thing.

I cover a few ways to do this on my blog.

For example, Python guarantees to evaluate the elements of a tuple in order, so we can use , much like an imperative ;. We can replace many statements, like print, with expressions, like sys.stdout.write.

Hence the following are equivalent:

```<code>def print_in_tag_def(tag, text):
    print "<" + tag + ">"
    print text
    print "</" + tag + ">"

import sys
print_ = sys.stdout.write
print_in_tag_lambda = lambda tag, text: (print_("<" + tag + ">"),
                                         print_(text),
                                         print_("</" + tag + ">"),
                                         None)[-1]
</code>```

Note that I've added a None at the end, and extracted it using [-1]; this sets the return value explicitly. We don't have to do this, but without it we'd get a funky (None, None, None) return value, which we may or may not care about.

So we can sequence IO actions. What about local variables?

Python's = forms an statement, so we need to find an equivalent expression. One way is to mutate the contents of datastructure, passed in as an argument. For example:

```<code>def stateful_def():
    foo = 10
    bar = foo * foo
    foo = 2
    return foo + bar

stateful_lambda = (lambda state: lambda *_: (state.setdefault('foo', 10),
                                             state.setdefault('bar', state.get('foo') * state.get('foo')),
                                             state.pop('foo'),
                                             state.setdefault('foo', 2),
                                             state.get('foo') + state.get('bar'))[-1])({})
</code>```

There are few tricks being used in stateful_lambda:

The *_ argument allows our lambda to take any number of arguments. Since this allows zero arguments, we recover the calling convention of stateful_def.

Calling an argument _ is just a convention which says "I'm not going to use this variable"

We have one ("wrapper") function returning another ("main") function: lambda state: lambda *_: ...

Thanks to lexical scope, the argument of the first function will be in-scope for the second function

Accepting some arguments now and returning another function to accept the rest later is known as currying

We immediately call the "wrapper" function, passing it an empty dictionary: (lambda state: ...)({})

This lets us assign a variable state to a value {} without using an assignment statement (eg. state = {})

We treat keys and values in state as variable names and bound values

This is less cumbersome than using immediately-called lambdas

This allows us to mutate the values of variables

We use state.setdefault(a, b) instead of a = b and state.get(a) instead of a

We use a tuple to chain together our side-effects, like before

We use [-1] to extract the last value, which acts like a return statement

Of course this is pretty cumbersome, but we can make a nicer API with helper functions:

```<code># Keeps arguments and values close together for immediately-called functions
callWith = lambda x, f: f(x)

# Returns the `get` and `setdefault` methods of a new dictionary
mkEnv = lambda *_: callWith({},
                            lambda d: (d.get,
                                       lambda k, v: (d.pop(k), d.setdefault(k, v))))

# A helper for providing a function with a fresh `get` and `setdefault`
inEnv = lambda f: callWith(mkEnv(), f)

# Delays the execution of a function
delay = lambda f x: lambda *_: f(x)

# Uses `get` and `set`(default) to mutate values
stateful_lambda = delay(inEnv, lambda get, set: (set('foo', 10),
                                                 set('bar', get('foo') * get('foo')),
                                                 set('foo', 2),
                                                 get('foo') + get('bar'))[-1])
</code>```

Body:
Hacking together a multi-statement lambda isn't quite as bad as pyrospade makes out: sure we could compose a bunch of monadic functions using bind, like in Haskell, but since we're in the impure world of Python, we might as well use side-effects to achieve the same thing.

I cover a few ways to do this on my blog.

For example, Python guarantees to evaluate the elements of a tuple in order, so we can use , much like an imperative ;. We can replace many statements, like print, with expressions, like sys.stdout.write.

Hence the following are equivalent:

def print_in_tag_def(tag, text):
    print "<" + tag + ">"
    print text
    print "</" + tag + ">"

import sys
print_ = sys.stdout.write
print_in_tag_lambda = lambda tag, text: (print_("<" + tag + ">"),
                                         print_(text),
                                         print_("</" + tag + ">"),
                                         None)[-1]

Note that I've added a None at the end, and extracted it using [-1]; this sets the return value explicitly. We don't have to do this, but without it we'd get a funky (None, None, None) return value, which we may or may not care about.

So we can sequence IO actions. What about local variables?

Python's = forms an statement, so we need to find an equivalent expression. One way is to mutate the contents of datastructure, passed in as an argument. For example:

def stateful_def():
    foo = 10
    bar = foo * foo
    foo = 2
    return foo + bar

stateful_lambda = (lambda state: lambda *_: (state.setdefault('foo', 10),
                                             state.setdefault('bar', state.get('foo') * state.get('foo')),
                                             state.pop('foo'),
                                             state.setdefault('foo', 2),
                                             state.get('foo') + state.get('bar'))[-1])({})

There are few tricks being used in stateful_lambda:

The *_ argument allows our lambda to take any number of arguments. Since this allows zero arguments, we recover the calling convention of stateful_def.

Calling an argument _ is just a convention which says "I'm not going to use this variable"

We have one ("wrapper") function returning another ("main") function: lambda state: lambda *_: ...

Thanks to lexical scope, the argument of the first function will be in-scope for the second function

Accepting some arguments now and returning another function to accept the rest later is known as currying

We immediately call the "wrapper" function, passing it an empty dictionary: (lambda state: ...)({})

This lets us assign a variable state to a value {} without using an assignment statement (eg. state = {})

We treat keys and values in state as variable names and bound values

This is less cumbersome than using immediately-called lambdas

This allows us to mutate the values of variables

We use state.setdefault(a, b) instead of a = b and state.get(a) instead of a

We use a tuple to chain together our side-effects, like before

We use [-1] to extract the last value, which acts like a return statement

Of course this is pretty cumbersome, but we can make a nicer API with helper functions:

# Keeps arguments and values close together for immediately-called functions
callWith = lambda x, f: f(x)

# Returns the `get` and `setdefault` methods of a new dictionary
mkEnv = lambda *_: callWith({},
                            lambda d: (d.get,
                                       lambda k, v: (d.pop(k), d.setdefault(k, v))))

# A helper for providing a function with a fresh `get` and `setdefault`
inEnv = lambda f: callWith(mkEnv(), f)

# Delays the execution of a function
delay = lambda f x: lambda *_: f(x)

# Uses `get` and `set`(default) to mutate values
stateful_lambda = delay(inEnv, lambda get, set: (set('foo', 10),
                                                 set('bar', get('foo') * get('foo')),
                                                 set('foo', 2),
                                                 get('foo') + get('bar'))[-1])


答:
Your approach in example 1, make the DAO call the constructor, gets very close to the Repository Pattern.

However, it makes more sense to have an actual repository do the coordination.

```<code>class SomeObjectRepository {
  SomeObjectDAO sod;
  ...
  SomeObject getSomeObject() {
    return new SomeObject(sod.getData1(), sod.getData2());
  }
}
</code>```

The DAO gets bound to the repository (a singleton) when it is created. Foo then calls the repository method to get the object.

This way, the object becomes decoupled from the DAO, the DAO performs only basic operations and they are more easily tested with respect to each other.

Title: Is it considered bad practice to make a DAO call in an object's constructor?

Body:
I am trying to figure out the best design for instantiating an object which requires two separate calls to the data layer through a DAO. The object is not usable until these calls have been made (because it requires the data retrieved from the database). I have come up with three possible solutions:

Create a method in the DAO itself that gets the necessary data from the database, and then pass the data to the object's constructor. The object is passed back as the return value.

Create a method in the class that is using the object. This method would make both calls to public methods in the DAO, then instantiate and return the object as in step 1.

Pass the DAO as a parameter to the constructor of the object. The constructor would then make both necessary calls to the DAO, setting its own member variables without the need for Setters. The DAO is not used other than in the constructor.

Examples, if SomeObject is the object I want to create, and Foo is the class that will make use of it:

1 - DAO Contains the logic:

```<code>public SomeObject getSomeObject(){ // this DAO method called by Foo class
     data1 = getData1();
     data2 = getData2();
     return new SomeObject(data1,data2);
}
</code>```

2 - Class that uses object contains the logic:

```<code>public class Foo {
    ...
         public void useSomeObject() {
              SomeObject obj = createSomeObject();
              obj.doStuff();
         }

         private SomeObject createSomeObject() {
              data1 = dao.getData1();
              data2 = dao.getData2();
              SomeObject someObject = new SomeObject(data1,data2);
              return someObject;
         }
}
</code>```

3 - SomeObject takes DAO as parameter and uses it in constructor:

```<code>public class SomeObject {
...
      public SomeObject(DAO dao) {
           data1 = dao.getData1();
           data2 = dao.getData2();
      }
...
 }
</code>```

Hopefully these examples are sufficient to convey my point. Are any of these solution considered better design than the others? If not, what solution is considered best practice?

Thanks.

Body:
Your approach in example 1, make the DAO call the constructor, gets very close to the Repository Pattern.

However, it makes more sense to have an actual repository do the coordination.

class SomeObjectRepository {
  SomeObjectDAO sod;
  ...
  SomeObject getSomeObject() {
    return new SomeObject(sod.getData1(), sod.getData2());
  }
}

The DAO gets bound to the repository (a singleton) when it is created. Foo then calls the repository method to get the object.

This way, the object becomes decoupled from the DAO, the DAO performs only basic operations and they are more easily tested with respect to each other.


答:
In classical OOP, the notion of encapsulation embodies the idea of combining data with code; that is, providing methods that act specifically on the data they represent.  So, for example, a Customer object contains only those methods which pertain specifically to customer "behavior."

Persisting objects is an orthogonal concern.

The Customer object should not know anything about how it is being saved or retrieved from a database, XML file, or whatever (the concept is called Persistence Ignorance).  This is why the preferred approach, especially in a large system, is to utilize some generalized persistence mechanism like an Object Relational Mapper to store and retrieve objects, and then to draw that functionality out through Repository methods that return objects or perform some business action on the data.

This relieves you of the responsibility of having to code a persistence implementation for each and every class you create.

Further Reading

The Unit Of Work Pattern And Persistence Ignorance


问:
Is having some logic in source code in order to perform some tests a good practice?
The question is not about changing the method/function visibility or extract local variable into instance variable in order to perform unit tests.

There are cases where we could include some logic in the source code in order to help us performing some functional tests or end-to-end tests. Generally speaking, these code interact with main logic directly and if the test code is defective, the business logic is affected.

One example could be that we have some test code around date/time logic so that if the testers make server and client time different, this code could help them to perform some tests.

So how bad you think having this is, if there is no other easy(ish) way to test this part of business logic?

Please comment if this plain explanation is too vague and you need more examples.

答:
Your problem calls for the IOC Pattern. Where ever you need a DateTime you will use the DateTimeProvider that you injected into your class as a constructor parameter.

Now when you are testing your class you can use your own mocked/dummy/whatever DateTimeProvider and do whatever your want.

Now your classes will not contain any test code. It may seem like extra boiler plate code, but in that case I recommend using an IOC container.


问:
In C++11 can Auto be used to get around mis-casting of void * parameters in functions?
If I have a generic function that takes a void* as a parameter, can Auto in C++11 help stop any bad casting of that parameter?

For instance, we may have an event system that sends events and a pointer to some data that is relevant for the event it sends.

```<code>void EventClass::SendEvent (eventTypeEnum eventType, void* eventData)
{
  int* castEventData = static_cast<int*> (eventData);

  //.. Do something
}
</code>```

In the above example, one eventType could be sent with eventData as a float* and another as a pointer to a structure.
The static_cast there will be mis-casting and causing problems.

Is there a way auto could be used to avoid this issue.

Please note, this is just an example (not a great one though sorry) to help me understand the possibilities of auto and not an actual issue I have.

答:
No, remember that 'auto' is a compile time feature: it says the compiler may infer the type of a variable from it's initializer. For example, if the compiler sees

```<code>auto i = 10;
</code>```

it can infer that i is an integer. Or more usefully, given

```<code>auto it = c.begin();
</code>```

where c is some sort of collection, the compiler can infer that it is an iterator of the appropriate subtype.

Here your function simply says that eventData is a void*, so that's all the compiler has to go on. Detecting that in a particular instance you've passed a float* rather than an int* is a run time issue and auto won't solve it.

I think some languages have used an 'auto' for a generic data type like Microsoft's 'Variant', but that's not what the 'auto' in C++ is providing.

It sounds like you need support for Run Time Type Identification (RTTI), but that still assumes some constraint on what you are passing in the function. If you truly need to be able to pass anything from a char* to a IncrediblyComplexStruct*, you probably are just going to have to pass the type along with the value, possibly using the eventTypeEnum as @RobertHarvey suggested.

Body:
No, remember that 'auto' is a compile time feature: it says the compiler may infer the type of a variable from it's initializer. For example, if the compiler sees

auto i = 10;

it can infer that i is an integer. Or more usefully, given

auto it = c.begin();

where c is some sort of collection, the compiler can infer that it is an iterator of the appropriate subtype.

Here your function simply says that eventData is a void*, so that's all the compiler has to go on. Detecting that in a particular instance you've passed a float* rather than an int* is a run time issue and auto won't solve it.

I think some languages have used an 'auto' for a generic data type like Microsoft's 'Variant', but that's not what the 'auto' in C++ is providing.

It sounds like you need support for Run Time Type Identification (RTTI), but that still assumes some constraint on what you are passing in the function. If you truly need to be able to pass anything from a char* to a IncrediblyComplexStruct*, you probably are just going to have to pass the type along with the value, possibly using the eventTypeEnum as @RobertHarvey suggested.


问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答:
It's natural, but I think it should be fought. Typically, I'll push on long past the point where I'm generating high-quality code, and I end up spending a lot of time in the morning fixing things that looked good when I was too tired to think straight.

I can usually tell when I'm getting irrational about it, but it helps to have someone around to slap you if you fail to heed the warning signs.

ContentLicense: CC BY-SA 2.5


答:
I'm generally in favor of nested functions, especially in JavaScript.

In JavaScript, the only way to limit a function's visibility is by nesting it inside another function.

The helper function is a private implementation detail.  Putting it at the same scope is akin to making a class' private functions public.

If it turns out to be of more general use, it's easy to move out, because you can be confident the helper is currently only used by that one function.  In other words, it makes your code more cohesive.

You can often eliminate parameters, which makes the function signature and implementation less verbose.  This is not the same thing as making variables global.  It's more like using a class member in a private method.

You can give the helper functions better, simpler names, without worrying about conflicts.

The helper function is easier to find.  Yes, there are tools that can help you.  It's still easier to just move your eyes up the screen a bit.

Code naturally forms a sort of tree of abstraction:  a few general functions at the root, branching out into several implementation details.  If you use an editor with function folding/collapsing, nesting creates a hierarchy of closely-related functions at the same level of abstraction.  That makes it very easy to study the code at the level you need and hide the details.

I think a lot of opposition comes from the fact that most programmers were either brought up in a C/C++/Java tradition, or were taught by someone else who was.  Nested functions don't look natural because we weren't exposed to them much when we were learning to program.  That doesn't mean they aren't useful.

Title: Should I place functions that are only used in one other function, within that function?

Body:
Specifically, I'm writing in JavaScript.

Let's say my primary function is Function A. If Function A makes several calls to Function B, but Function B is not used anywhere else, then should I just place Function B within Function A?

Is that good practice? Or should I still put Function B at the same scope as Function A?


问:
Testing strategy for production environment
In an ideal world, dev/ops are working together as one team to release something onto production.

However, there are organizations with limitations so that release engineers/teams are kept completely away from development/project teams.

This not only added the communication pain for releases but also making the production environment almost "invisible" to project team. To some extent, there is "trust crisis" between project and deployment team.

Even we have good and reliable Acceptance/Functional tests in UAT environment but we just not sure if the deployment process has been done properly and if everything works on production exactly as UAT. So the only way we can verify this is through some tests on production environment.

Some simple smoke tests could be helpful to identify connectivity problems.

So my question is : What's your opinion on applying all tests we had on UAT to production (with configuration to disable the bits that we don't want to happen on production such as removing data etc.)

If you have done something similar, how do you play data on production environment without having audit trails tainted (one obvious thing would be account based, but let's assume there isn't segregation by account).

EDIT: I didn't mean to test prod environment all the time, but only right after deployment.
Also we will not stop trying solving the problem from the root - dev/op relationship. But at the same time would like to explore other possibilities.

答:
Usually, tests are performed outside production servers for three reasons:

Safety. If something goes wrong and all data from staging is accidentally removed, you don't care. If it happens in production, it's... let's say annoying.

Performance. An extensive suite of tests can easily use 100% CPU on several servers for several minutes. You can't afford slowing down production servers for a few minutes ten times per hour.

Goal. The goal of testing is to prevent issues in production. If you find an issue when the application is already deployed, it's too late. Moreover, reverting to the previous revision can be complicated. For example, what if the new version created a column in the database, and meanwhile, you have new records where this new column was used?

For those reasons, I would strongly advise you against the usage of production environment for testing. Moreover, I don't think running tests in production and sending the results back to your team will help to gain the trust of system administrators; they may perceive that as a tentative to circumvent the limitations they set to protect their infrastructure from your team.

Instead, address the original issue, i.e. the lack of trust between developers and system administrators. Until communication and trust issues exist on this level, the testing and deployment process will  be painful, no matter what tricks you'll use to make it easier.


问:
Eliminate duplicate code in nested IFs without creating a function
Let's say we have two ifs that depend on each other:

```<code>if var exists {
    if var is array {
        //Do stuff with var
    } else {
        //Resolve the problem
    }
} else {
    //Resolve the problem in the exact same way as above
}
//Continue execution with the assumption that var is in the appropriate state
</code>```

How can I refactor this to remove the duplicated code without using gotos or functions/methods?

答:
If you don't mind "do stuff with var" runs every time:

```<code>if var does not exist {
    //Resolve the problem
}

if var is array {
    //Do stuff with var
}
//Continue execution with the assumption that var is in the appropriate state
</code>```

If you don't want "do stuff with var" to run every time (as in original code):

```<code>if var does not exist {
    //Resolve the problem
    flag = true
}

if var is array && flag == true {
    //Do stuff with var
}
//Continue execution with the assumption that var is in the appropriate state
</code>```

Body:
If you don't mind "do stuff with var" runs every time:

if var does not exist {
    //Resolve the problem
}

if var is array {
    //Do stuff with var
}
//Continue execution with the assumption that var is in the appropriate state

If you don't want "do stuff with var" to run every time (as in original code):

if var does not exist {
    //Resolve the problem
    flag = true
}

if var is array && flag == true {
    //Do stuff with var
}
//Continue execution with the assumption that var is in the appropriate state


答:
Am I missing something more complicated here, or shouldn't this just be:

```<code>if var exists and var is array {
    //Do stuff with var
} else {
    //Resolve the problem
}

//Continue execution with the assumption that var is in the appropriate state
</code>```

The check for if var exists will short-circuit and fall through to the else resolution block if it evaluates to false.

Title: Eliminate duplicate code in nested IFs without creating a function

Body:
Let's say we have two ifs that depend on each other:

```<code>if var exists {
    if var is array {
        //Do stuff with var
    } else {
        //Resolve the problem
    }
} else {
    //Resolve the problem in the exact same way as above
}
//Continue execution with the assumption that var is in the appropriate state
</code>```

How can I refactor this to remove the duplicated code without using gotos or functions/methods?

Body:
Am I missing something more complicated here, or shouldn't this just be:

if var exists and var is array {
    //Do stuff with var
} else {
    //Resolve the problem
}

//Continue execution with the assumption that var is in the appropriate state

The check for if var exists will short-circuit and fall through to the else resolution block if it evaluates to false.


答:
I'm going to propose a third path, to place both functions within a closure. It would look like:

```<code>var functionA = (function(){
    function functionB() {
        // do stuff...
    }

    function functionA() {
        // do stuff...
        functionB();
        // do stuff...
    }

    return functionA;
})();
</code>```

We create the closure by wrapping the declaration of both functions in a IIFE. The return value of the IIFE is the public function, stored in a variable of the name for the function. The public function can be invoked in exactly the same way as if it were declared as a global function, ie functionA(). Note that the return value is the function, not a call to the function, thus no parens at the end.

By wrapping the two functions up like so, functionB is now completely private, and cannot be accessed outside of the closure, but is visible only to functionA. It is not cluttering the global namespace, and is not cluttering the definition of functionA.

Body:
I'm going to propose a third path, to place both functions within a closure. It would look like:

var functionA = (function(){
    function functionB() {
        // do stuff...
    }

    function functionA() {
        // do stuff...
        functionB();
        // do stuff...
    }

    return functionA;
})();

We create the closure by wrapping the declaration of both functions in a IIFE. The return value of the IIFE is the public function, stored in a variable of the name for the function. The public function can be invoked in exactly the same way as if it were declared as a global function, ie functionA(). Note that the return value is the function, not a call to the function, thus no parens at the end.

By wrapping the two functions up like so, functionB is now completely private, and cannot be accessed outside of the closure, but is visible only to functionA. It is not cluttering the global namespace, and is not cluttering the definition of functionA.


问:
Use constructor or setter method?
I am working on a UI code where I have an Action class, something like this -

```<code>public class MyAction extends Action {
    public MyAction() {
        setText("My Action Text");
        setToolTip("My Action Tool tip");
        setImage("Some Image");
    }
}
</code>```

When this Action class was created, it was pretty much assumed that the Action class won't be customizable (in a sense - its text, tooltip or image will be not be changed anywhere in the code). Now, we are in need of changing the action text at some location in code. So, I suggested my co-worker to remove the hardcoded action text from the constructor and accept it as an argument, so that everybody is forced to pass the action text. Something like this code below -

```<code>public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip");
        setImage("My Image");
    }
}
</code>```

He, however, thinks that since setText() method belongs to base class it can be flexibly used to pass the action text wherever action instance is created. That way, there is no need to change the existing MyAction class. So his code would look something like this.

```<code>MyAction action = new MyAction(); //this creates action instance with the hardcoded text
action.setText("User required new action text"); //overwrite the existing text.
</code>```

I am not sure if that is a correct way to deal with problem. I think in above mentioned case user is anyway going to change the text, so why not force him while constructing the action? The only benefit I see with the original code is that user can create Action class without much thinking about setting text.

答:
The advice to use constructors or builders is fine in general, but, in my experience, misses some key points for Actions, which

Possibly need to be internationalized

Are likely for marketing to change at the last minute.

I strongly suggest that the name, tooltip, icon etc... be read from a properties file, XML, etc.  For example, for the File-Open action, you could pass in a Properties and it would look for

```<code>File.open.name=Open
File.open.tooltip=Open a file
File.open.icon=somedir/open.jpg
</code>```

This is a format pretty easy to translate to French, to try a new better icon, etc.  Without programmer time or a recompile.

This is just a rough outline, a lot is left to the reader...  Look for other examples of internationization.

Title: Use constructor or setter method?

Body:
The advice to use constructors or builders is fine in general, but, in my experience, misses some key points for Actions, which

Possibly need to be internationalized

Are likely for marketing to change at the last minute.

I strongly suggest that the name, tooltip, icon etc... be read from a properties file, XML, etc.  For example, for the File-Open action, you could pass in a Properties and it would look for

File.open.name=Open
File.open.tooltip=Open a file
File.open.icon=somedir/open.jpg

This is a format pretty easy to translate to French, to try a new better icon, etc.  Without programmer time or a recompile.

This is just a rough outline, a lot is left to the reader...  Look for other examples of internationization.


问:
What to do with a long unfinished project?
I am a programmer hobbyist (self learnt), and once in a while I like to make games and interactive scripts (nowadays mostly in JavaScript for its ease).

Sometimes I start long projects that end up being forgotten because of other things I have to do.

Sometimes a project gets really big (say, 3000 lines is a huge deal to me).

My code is mostly uncommented, unorganized, and unoptimised and some of my projects are never finished.

Question:

What do programmers (or teams), do with such projects ?

Is there a recommended practice regarding this issue in the "real world"?

答: You can first do us a favor and stop writing big, hard-coded, uncommented, 3k lines of code. Some of us (myself) like to code for fun and are willing to continue the project, if you just post it up on GitHub for the community.</p>


答:
I have a simple counter question for you: what do you want to do with those?

Personally, my take on this is if it's a hobby, you should do only what is fun for you. Nothing else. If it spells work for you, or a big time investment, then just forget about it.

You should not think of these projects as a sort of failure in any way. I have dozens, maybe hundreds of these things lying around or already discarded, and I don't worry about that for even a millisecond. As opposed to you, I am a professional developer, so these are my practice playgrounds. I toy around with new technology, interesting ideas, etc. and I never plan to make a huge kick-ass game out of it that hundreds or thousands of players will play. If you keep your naivety under control and start your projects without having such a dream, then not finishing it all up is perfectly fine. If you want something to show for the time you spent on this hobby, then you should maybe switch from games to graphic demos, i.e. switch to something with a much much shorter time-frame needed for its completion. But as you already learned - getting those last 5% done takes about as long as the first 95% took.

Finally, if you have any plans to turn this hobby into a career, then don't throw away the code. Just let it rest. Come back to your old code after a year or two for a very instructive experience. It will show you how much better you got in the meantime - the typical reaction to one's old code is "oh my.. did I really write code like that once?". And if you take the project on again, you'll get some valuable experience with regards to developing with legacy code bases. By the time you will have forgotten all of the intricate details, all of your great design plans. Your documentation may be outdated and your dependencies may no longer be available, etc etc. in short: you got yourself the real world deal. Be warned though: this is not even remotely as fun as writing your own stuff from scratch, so I'd only advise to go down that rabbithole if you want to get farther than it just being a hobby.

In summary: stop worrying. Adjust your view of what you want to get out of the hobby and accept the consequences.

Title: What to do with a long unfinished project?

Body:
I am a programmer hobbyist (self learnt), and once in a while I like to make games and interactive scripts (nowadays mostly in JavaScript for its ease).

Sometimes I start long projects that end up being forgotten because of other things I have to do.

Sometimes a project gets really big (say, 3000 lines is a huge deal to me).

My code is mostly uncommented, unorganized, and unoptimised and some of my projects are never finished.

Question:

What do programmers (or teams), do with such projects ?

Is there a recommended practice regarding this issue in the "real world"?


答:
Indeed I recognize this. I can obsess over a problem all night until I just have to give up, exhausted and frustrated. Brain Fog.

The funny thing is that I usually manage to solve the problem right away when I get back to work in the morning. I guess that's because my brain works much better after a good sleep.

What I have learned from all this is that there is no point in working all nighters since the brain is many times more effective when it is well rested and energized. At least for me, but I suspect this is the same for everyone.

Also see sustainable pace and death march.

Title: What to do about "stopping point syndrome"?

Body:
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?


问:
Why are deadlines always so short?
I'm a junior developer in a small company (in a team of 2 developers). Everytime we are asked to implement a new feature:

the deadline is set so that we just have time to do the development: there is no error margin (if something takes a little bit more time than expected, we are late) ; almost no time for tests (we are pretty sure there will be bugs) ; no time to refactor anything

we are asked to start the development before the features are completely specified, so new things to do show up but the deadline stays as it is

The result is that we deliver software that has bugs and the technical debt keeps growing. We use technology that was considered as a recent version in 2006 or so.

There was one release that I remember very well. When we did a demonstration to the boss, he told us "What!?? You took two weeks to produce that?!" and all we could answer was "No, in fact it took us three weeks". I had a meeting with him and another junior developer (that quit the company because of this said meeting!), and he basically told us that he was not happy because what we released was crap.

The technical debt and the need to refactor were so big in the parts that we had to modify (but we were told not to refactor because we have no time) that:

we had to add a layer of bad code on top of the already bad code;

we took much time to try and understand completely incomprehensible code.

I don't feel like I'm responsible for this bad release, I think that it's the boss' responsibility to hire good developers that, at least, understand the basic principles of OOP. But hiring juniors is so much less expensive...

He is already saying that we are late for the development I'm working on at the moment. He spent more than one year to "redesign" a tool that was already present in our application, but now he wants us to implement it in two weeks. I personally think that if we want to do it correctly, we need at least one month, or maybe even 6 weeks.

I don't know what to do, because I think that the boss thinks that we are just slow and ineffective. That's not the way I will get the raise I think I deserve.

Why is it like that? That doesn't seem so hard to understand that if I need x days to complete a task, I can't do it in x/2 days, even if you say "please" and ask with a smile. That seems so obvious that the deadline will be missed and/or that the quality requirements won't be met.

I don't need to know how I can explain to my boss that software development is a longer process that just clicking an icon. Because I hope he already knows that.

答:
Two choices really: Quit, or grow a backbone.

I think I don't have to explain much about quitting.. that one is obvious. If you can neither take it nor dare to change it, it's the only way to go forward.

If you do want to change this, then it is your responsibility to stand up against this. This does need "a backbone", because you will be going against your boss and being fired is a real possibility there! So tread with caution, but stop being pushed around.

Why am I saying that you're pushed around? Well, of course, junior devs are easier to push around than seniors, because they lack experience, but, there is one fundamental issue you seem to totally have missed here (which got pushed past you so to say) : Deadlines are best made by the developers, not by management.

If your boss or some manager says it takes 2 weeks and you think that is is too short, then professional behavior dictates that you inform your superiors of this insight. After all, you are the developer who is going to spend those 2 weeks doing the work. There is no one - absolutely no one - who is more qualified to judge the correctness of this estimate than you! Your managers may resort to prior experience or other teams' performances, but you know the real deal. You know the particular code base, its weaknesses, its risks, etc. There is no way that any meaningful deadline can be made without your input.

Refactoring: This is an interesting topic always and there are many good reads on how to incorporate it into a schedule. The gist of these though is that a) you will never ever get time dedicated for refactoring from your manager and b) you shouldn't even ask for that, because even when you get it, it'll not be enough. Refactoring is something that must become part of your every day work. It must be part of your estimates, and it is part of what you are doing. So much that you need not even mention it towards management. This is how we work professionally after all. You may skip it once or twice remarking that the next deadlines need to account for that, but if you cannot make it up, then the professional way is to get it done right the first time. Of course, you have to keep a balance and not refactor the whole code base first for half a year. Stick to what you are working on anyways and try to keep the technical debt instead of increasing it, if possible even reduce it a little.

When a deadline approaches - in particular if the deadline was given to you from outside sources without your approval - it is fair game to simply tell them that you are not done. If you said from the start that 2 weeks will not be enough, then no one can blame you for not being finished after 2 weeks. The way from junior to senior dev means learning to be able to keep a straight face when telling your managers that it is not done due to their decisions. Keep in mind that if you estimated 4 weeks, but were required to deliver within 2 weeks, that any delay is not your fault.

Nevertheless, managers will try to blame you / your team for any delays. If you want to keep going with this company, then you face an even tougher challenge: you have to change your managers mind! You have to remind them that it is not about assigning blame, but about providing value to the business. You are supposed to work together, not against each others, but from what you tell it seems that there is a big trust problem between developers and management. Standing up against ridiculous deadlines is one thing, but it will only get you so far. If you have to constantly fight your managers, then you are bound to fail (both sides actually).

In summary, if you believe you are strong enough and can keep up with the pressure and stress, then you should 1) ensure you are part of the deadline decision from the beginning and 2) improve confidence and trust between developers and managers. The first is comparatively quick and easy, whereas the latter is a slow and delicate process that may well take you years.

Title: Why are deadlines always so short?


答:
There are a lot of reasons why deadlines will always be tight.

One of the main theories here is Parkinson's law.

Parkinson states: "Work expands so as to fill the time available for its completion".

So, if you have a project that would take 3 months and you get a 6 month deadline? How long would it take? 6 Months of course, because there's always something that can be improved.

By setting tighter deadlines, management tries to bring out the best in people. The power of tight deadlines.

There are a lot of reasons to set tight deadlines, some good, some bad.
There are also a lot of good and bad managers, who do or don't understand management theory.

Title: Why are deadlines always so short?

Body:
I'm a junior developer in a small company (in a team of 2 developers). Everytime we are asked to implement a new feature:

the deadline is set so that we just have time to do the development: there is no error margin (if something takes a little bit more time than expected, we are late) ; almost no time for tests (we are pretty sure there will be bugs) ; no time to refactor anything

we are asked to start the development before the features are completely specified, so new things to do show up but the deadline stays as it is

The result is that we deliver software that has bugs and the technical debt keeps growing. We use technology that was considered as a recent version in 2006 or so.

There was one release that I remember very well. When we did a demonstration to the boss, he told us "What!?? You took two weeks to produce that?!" and all we could answer was "No, in fact it took us three weeks". I had a meeting with him and another junior developer (that quit the company because of this said meeting!), and he basically told us that he was not happy because what we released was crap.

The technical debt and the need to refactor were so big in the parts that we had to modify (but we were told not to refactor because we have no time) that:

we had to add a layer of bad code on top of the already bad code;

we took much time to try and understand completely incomprehensible code.

I don't feel like I'm responsible for this bad release, I think that it's the boss' responsibility to hire good developers that, at least, understand the basic principles of OOP. But hiring juniors is so much less expensive...

He is already saying that we are late for the development I'm working on at the moment. He spent more than one year to "redesign" a tool that was already present in our application, but now he wants us to implement it in two weeks. I personally think that if we want to do it correctly, we need at least one month, or maybe even 6 weeks.

I don't know what to do, because I think that the boss thinks that we are just slow and ineffective. That's not the way I will get the raise I think I deserve.

Why is it like that? That doesn't seem so hard to understand that if I need x days to complete a task, I can't do it in x/2 days, even if you say "please" and ask with a smile. That seems so obvious that the deadline will be missed and/or that the quality requirements won't be met.

I don't need to know how I can explain to my boss that software development is a longer process that just clicking an icon. Because I hope he already knows that.


答:
Provided you've implemented a robust version control system you spread the tests out so that you just need to confirm basic functionality.

As an example the following are done in the four environments (simplified for brevity):

DEV: Unit tests, some behavioural tests

FAT: Integration tests, regression tests, installation tests

UAT: Test of deployment to LIVE (possibly with faux data)

LIVE: Common functionality, possible environment testing

DEV (Development) environment

The focus is on unit tests to test the new functionality, bug fixes, and the previous tests; some behavioural tests can be performed if required for new/modified functionality.

FAT (Factory Acceptance Test) environment

You test your installers and allow your testers to run through the application and test the new functions, bug fixes, and to ensure the old functionality isn't broken through regression testing.

UAT (User Acceptance Test) environment

Your client/customers/users test your application to ensure it works according to their expectations.  Of note is that UAT should be identical to LIVE so what works here should work in LIVE.

LIVE (Production) environment

You just need to get the update to the latest version done, and recheck basics (smoke-tests): can access data, open reports, view documents, export/import data, etc.

By the time software gets to the LIVE environment is it has passed all the previous environments without issue, so there is no need to retest; if any environment fails for any reason the software release goes back to DEV, changes are made, and the whole process starts again under a new release number e.g. 1.2.3.0 -> 1.2.3.1.

You build trust in your release to LIVE by going through each environment and completing tests so that you don't need to retest in LIVE.

Title: Testing strategy for production environment

Body:
In an ideal world, dev/ops are working together as one team to release something onto production.

However, there are organizations with limitations so that release engineers/teams are kept completely away from development/project teams.

This not only added the communication pain for releases but also making the production environment almost "invisible" to project team. To some extent, there is "trust crisis" between project and deployment team.

Even we have good and reliable Acceptance/Functional tests in UAT environment but we just not sure if the deployment process has been done properly and if everything works on production exactly as UAT. So the only way we can verify this is through some tests on production environment.

Some simple smoke tests could be helpful to identify connectivity problems.

So my question is : What's your opinion on applying all tests we had on UAT to production (with configuration to disable the bits that we don't want to happen on production such as removing data etc.)

If you have done something similar, how do you play data on production environment without having audit trails tainted (one obvious thing would be account based, but let's assume there isn't segregation by account).

EDIT: I didn't mean to test prod environment all the time, but only right after deployment.
Also we will not stop trying solving the problem from the root - dev/op relationship. But at the same time would like to explore other possibilities.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
My first sign on one was when they asked how many hours of overtime we each would commit to for the next ten weeks and offered salaried workers a bonus for working said overtime based on the success of the project and meeting deadlines.

Other major signs I've seen:
Requirements defintion goes over schedule and the end date is not moved. We were behind before we can even start. They took the time away from design, so we started with no database design and no site design but expected to deliver on time by, among other things, doing imports to tables not designed and created yet.

When items on the critical path are being done simultaneously instead of in order. (If I'm required to use tool X and programmer A is just starting to build it, it is going to delay my task.)

When managers are committing code on Thanksgiving.

When you start getting emails that have a datetime stamp of later than 11 pm and earlier than 6 am.

When every question about how to handle some complexity is met with the same answer, "Don't worry about that yet."

When they are still making requirements changes the day betore you go to QA or go live.

When you start having daily meetings that take several hours to discuss your lack of progress. Oh that would be because I'm in meetings all day. Daily 5 minute meeting fine, daily meeting that goes over an hour, not fine.

When the database team and the aplication team don't talk to each other.

When the client can't provide the promised information on time. Especially when those are data import files and you need that data in the database to check to see how the code is working.

When you consider installing a stop light outside some manager's office to let you know if it is safe to approach him that day.


问:
Why have hardware-accelerated vector graphics not taken off?
I'm working on an app that involves real-time manipulation of vector paths at 60fps, and I'm very surprised by how little information there is on the subject. At first, I tried to implement my idea using CoreGraphics, but it didn't perform adequately for my purposes. I then discovered that there was a Khronos standard for hardware-accelerated vector graphics called OpenVG, and thankfully a kind soul had written an OpenGL ES semi-implementation called MonkVG.

But despite the fact that OpenVG is a very practically useful API, it seems more or less abandoned by Khronos. According to Wikipedia, since 2011, the working group "decided to... not make any regular meeting [sic] for further standardization". The documentation, best I can find, consists of just a single reference card. And what's more, there are barely any examples of OpenVG anywhere on the internet. I can find hundreds of OpenGL tutorials in the blink of an eye, but OpenVG seems conspicuously missing.

You'd think that hardware-accelerated vectors would be more important in today's world of rapidly-increasing resolutions, and it does seem that many companies are implementing their own ways of doing this. For example, Qt and Flash have schemes for hardware-accelerated vectors, and many of Adobe's tools have hardware acceleration as an option. But it seems like the wheel is getting reinvented when a standard already exists!

Is there something I'm missing about OpenVG that makes it unsuitable for real-world use? Or is it just that the standard didn't catch on in time and now it's destined for obscurity? Do you think there's room for a standardized API for hardware-accelerated vector graphics in the future, or will it just be easier to use traditional raster-based techniques? Or are vectors simply on their way out, before they were ever in?

答:
I don't think it is really true that nobody really cares about "accelerated vector graphics" as written in this answer.

Nvidia seems to care a fair bit. Besides Kilgard who is the lead technical guy on NV_path_rendering (henceforth NVpr to save my fingers), the Khronos president, Neil Trevett, who is also a VP at Nvidia, has promoted NVpr as much as he could in past couple of years; see his talk1, talk2 or talk3. And that seems to have paid off a bit. As the time of this writing, NVpr is now used in Google's Skia (which in turn is used in Google Chrome) and independently [of Skia] in a beta version of Adobe Illustrator CC (beta), according to Kilgard's slides at GTC14; there are also some videos of the talks given there: Kilgard's and Adobe's. A Cairo dev (who works for Intel) also seems interested in NVpr. Mozilla/Firefox devs also experimented with NVpr and they do in fact care about GPU accelerated vector graphics in general as this FOSDEM14 talk shows.

Microsoft also cares a fair bit because they created Direct2D, which is used fairly widely [if you believe the Mozilla dev from the aforementioned talk].

Now to get to the point of the original question: there are indeed some technical reasons why using GPUs for path rendering is not straightforward. If you want to read about how path rendering differs from bog-standard 3D vertex geometry and what makes GPU acceleration of path rendering non-trivial, then Kilgard has a very good FAQ-like post, which is unfortunately buried somewhere in the OpenGL forum.

For more details on how Direct2D, NVpr and such work, you could read Kilgard's Siggraph 2012 paper, which of course is focused on NVpr, but also does a good job surveying prior approaches. Suffice to say that quick hacks don't work too well... (as the text of the PSE question noted.) There are significant performance differences between these approaches as discussed in that paper and shown in some of Kilgard's early demos, e.g. in this video. I should also note that official NVpr extension document details several performance tunings over the years.

Just because NVpr wasn't so great on Linux in 2011 (in its first released implementation), as that 2011 blog post of Qt's Zack Rusin said, it doesn't mean that GPU acceleration of vectors/paths is hopeless as Mr. Goldberg's answer appears to have inferred from that. Kilgard has in fact replied to the end of that blog post with updated drivers showing 2x-4x improvement over Qt's faster code and Rusin hasn't said anything after that.

Valve Corp. also cares about GPU-accelerated vector rendering, but in a more limited way, relating to font/glyph rendering. They've had a nice, fast implementation of large font smoothing using GPU-accelerated signed distance fields (SDF) presented at Siggraph 2007, which is used in their games like TF; there's a video demonstration of the technique posted on YouTube (but I'm not sure who made that).

The SDF approach has seen some refinements by one of the Cairo & pango devs in the form of GLyphy; its author gave a talk at linux.conf.au 2014. The too-long-didn't-watch version is that he does an arc-spline approximation of the Bezier curves in order to make the SDF computation more tractable in vector (rather than in raster) space (Valve did the latter). But even with the arc-spline approximation, the computation was still slow; he said his first version ran at 3 fps. So he now does some grid-based culling for stuff that's "too far away", which looks like form of LOD (level of detail) but in the SDF space. With this optimization his demos ran at 60 fps (and it was probably Vsync limited). However his shaders are incredibly complex and push the limits of hardware and drivers. He said something along the lines of: "for every driver/OS combination we had to change things". He also found significant bugs in shader compilers, some of which were then fixed by their respective devs. So it sounds a lot like AAA gaming titles development...

On another tack, it appears that Microsoft has commissioned/specified a little bit of new GPU hardware to improve their Direct2D implementation with, hardware which is used by Windows 8, if available. This is called target-independent rasterization (TIR), a name which is a bit misleading as to what the stuff actually seems to do, which is spelled out in Microsoft's patent application. AMD claimed that TIR improved performance in 2D vector graphics by some 500%. And there was a bit of "war of words" between them and Nvidia because Kepler GPU's don't have it, whereas AMD's GCN-based GPUs do. Nvidia has confirmed that this is indeed a little bit of new hardware, not simply something a driver update can provide. Sinofsky's blog post has a few more details, including some actual benchmarks of TIR. I'm quoting only the general idea bits:

to improve performance when rendering irregular geometry (e.g. geographical borders on a map), we use a new graphics hardware feature called Target Independent Rasterization, or TIR.

TIR enables Direct2D to spend fewer CPU cycles on tessellation, so it can give drawing instructions to the GPU more quickly and efficiently, without sacrificing visual quality. TIR is available in new GPU hardware designed for Windows 8 that supports DirectX 11.1.

Below is a chart showing the performance improvement for rendering anti-aliased geometry from a variety of SVG files on a DirectX 11.1 GPU supporting TIR: [chart snipped]

We worked closely with our graphics hardware partners [read AMD] to design TIR. Dramatic improvements were made possible because of that partnership. DirectX 11.1 hardware is already on the market today and we’re working with our partners to make sure more TIR-capable products will be broadly available.

I guess this was one of the nice things that Win 8 added that was mostly lost to the world in the Metro UI fiasco...

ContentLicense: CC BY-SA 4.0


问:
How to convert this recursive problem to iterative? Line Simplification algorithm fails to run due to Maximum Recursion Depth being hit
I am implementing the Douglas, Peucker's Line Simplification algorithm in Python. I started with this implementation. However, it fails to run in Python due to Maximum Recursion Depth being hit. How can I convert this algorithm to a iterative one? I am not able to imagine this problem in an iterative view.

My expectation is to get approach/hint which can be used rather than actual code. Is it possible to use some internal stack to resolve the stack overflow (or avoid the maximum recursion depth)?

Update:
Found the iterative implementation of the algorithm here.

答:
Converting a recursive algorithm to be iterative usually involves doing the same thing that the compiler or interpreter does behind the scenes yourself, i.e. on front of the scenes. That can mean you have to program a call stack and keep track of the variable values in recursive calls yourself, so that they live in a user-defined data structure rather than on the system-provided call stack. It's more effort and usually less readable than using proper recursion, but it can allow you to circumvent system limitations - rather than hitting the built-in recursion limit you only hit the built-in limit on the size of dynamically allocated data.

Of course, it's also often possible to solve the same problem iteratively in a completely different way, sometimes even better. But then it's not so much converting the recursion as replacing it with something completely different. It depends on the problem whether that is possible or not.


答:
Why are deadlines always so short ?

Because managers like the one in your story hijack the estimation process and impose their own views onto developers. Oftentimes this is because they are former developers themselves and think they can come up with good estimates thanks to their experience.

In an ideal world, managers would trust programmers and let them take responsibility for producing estimates, like you'd do with any self-respecting professional. Client-defined deadlines would be met not by deteriorating quality but negotiating scope with the client.

Title: Why are deadlines always so short?


问:
Single Identity for Desktop and Web
I'm building a system has both a WPF desktop application as well as an Asp.net MVC application.

I need a common user identity component so that user can log on to either one with the same credentials.

Is ASP.NET Identity appropriate for this task?

Has anyone used ASP.NET Identity with a WPF application?

Are there any alternatives?

答:
Maybe something like OpenID Connect built on top of oAuth 2.0 would be applicable?

Users can manage their identities with an Identity Provider.
Your Web and Desktop applications become Relying Parties and they will be given an ID Token and possibly an Access Token when the user is authenticated with the Identity Provider.

The Identity Provider could be extended to federate onto other Identity Providers such as ADFS, Google, Facebook...

Title: Single Identity for Desktop and Web


答:
I would simulate in the most generic way as follows:
This is what I believe the low-level machine would do.

```<code>func(Param x) {

  Stack stack = new Stack();
  Frame frame = new Frame(x);
  push(frame);

  while (!stack.empty()) {
    frame = stack.pop();

    if (baseCase) {
       createResult(frame);
    } else {
       newFrame = doWork(frame);
       stack.push(frame);
       stack.push(newFrame);
    }
  }

  return frame.getResult();
}
</code>```

You can define Frame as follows:

```<code>class Frame {
   FrameData state;
   Data sharedData;
   Param inputParam;

   Result getResult() {
     ..compute result from 'state' and 'sharedData'
   }
}
</code>```

Now you can wonder why there is only one push into the stack even though you have 2 recursive calls. It is because The first recursive call is pushed into the stack with a frame having different state and sharedData compared to the frame pushed into the stack by the second call.

Since you said, you only want approach and hint. I hope this is enough. The details is done in the method doWork(). There Frame's instances variables are changed.

I took me a while to come up with this. Hopefully, there is nothing wrong here.

Title: How to convert this recursive problem to iterative? Line Simplification algorithm fails to run due to Maximum Recursion Depth being hit

Body:
I am implementing the Douglas, Peucker's Line Simplification algorithm in Python. I started with this implementation. However, it fails to run in Python due to Maximum Recursion Depth being hit. How can I convert this algorithm to a iterative one? I am not able to imagine this problem in an iterative view.

My expectation is to get approach/hint which can be used rather than actual code. Is it possible to use some internal stack to resolve the stack overflow (or avoid the maximum recursion depth)?

Update:
Found the iterative implementation of the algorithm here.

Body:
I would simulate in the most generic way as follows:
This is what I believe the low-level machine would do.

func(Param x) {

  Stack stack = new Stack();
  Frame frame = new Frame(x);
  push(frame);

  while (!stack.empty()) {
    frame = stack.pop();

    if (baseCase) {
       createResult(frame);
    } else {
       newFrame = doWork(frame);
       stack.push(frame);
       stack.push(newFrame);
    }
  }

  return frame.getResult();
}

You can define Frame as follows:

class Frame {
   FrameData state;
   Data sharedData;
   Param inputParam;

   Result getResult() {
     ..compute result from 'state' and 'sharedData'
   }
}

Now you can wonder why there is only one push into the stack even though you have 2 recursive calls. It is because The first recursive call is pushed into the stack with a frame having different state and sharedData compared to the frame pushed into the stack by the second call.

Since you said, you only want approach and hint. I hope this is enough. The details is done in the method doWork(). There Frame's instances variables are changed.

I took me a while to come up with this. Hopefully, there is nothing wrong here.


问:
Confused about javascript module pattern implementation
I have a class written on a project I'm working on that I've been told is using the module pattern, but it's doing things a little differently than the examples I've seen. It basically takes this form:

```<code>(function ($, document, window, undefined) {

    var module = {
        foo : bar,

        aMethod : function (arg) {
            className.bMethod(arg);
        },
        bMethod : function (arg) {
            console.log('spoons');
        }
    };
    window.ajaxTable = ajaxTable;

})(jQuery, document, window);
</code>```

I get what's going on here.
But I'm not sure how this relates to most of the definitions I've seen of the module (or revealing?) module pattern. like this one from briancray

```<code>var module = (function () {
    // private variables and functions
    var foo = 'bar';

    // constructor
    var module = function () {
    };

    // prototype
    module.prototype = {
        constructor: module,
        something: function () {
        }
    };

    // return module
    return module;
})();

var my_module = new module();
</code>```

Is the first example basically like the second except everything is in the constructor? I'm just wrapping my head around patterns and the little things at the beginnings and endings always make me not sure what I should be doing.

答:
It's really a weird example, I've never seen a usage of a constructor to create a module this way. I would higly recommend you using the first solution, it creates just one scope and one object and that's all you need. The second one is used mainly when you need to export some constructor. And then you are allowed to use new Constructor() multiple times. However the first solution can be a little bit altered:

```<code>var module = new (function ($, document, window, undefined) {
  this.property = "hello";
})(jQuery, document, window);

console.log(module.property);
</code>```

This allow you to create an IIFE which itself is a constructor so you get a new object based on this constructor. If you don't like the object literal based solution, this is a way to go.

Also you can take a look at AMD (using RequireJS) or CommonJS (using Node.js or Browserify) specifications which allows you to move every single module to its own file. Lots of libraries use these patterns. I prefer CommonJS and it's very simple. You have a file which represents a module and which has 3 additional predefined variables. They are exports, module and require.

```<code>// a.js
exports.property = "hello"; // Basically the same as the example above

// b.js
module.exports = function () { // Something similar to exporting a custom object
  console.log("hello");
};

// c.js
var a = require("./a"), b = require("./b"); // Loading these modules

console.log(a.property); // logs "hello"
b(); // also logs "hello"
</code>```

Body:
It's really a weird example, I've never seen a usage of a constructor to create a module this way. I would higly recommend you using the first solution, it creates just one scope and one object and that's all you need. The second one is used mainly when you need to export some constructor. And then you are allowed to use new Constructor() multiple times. However the first solution can be a little bit altered:

var module = new (function ($, document, window, undefined) {
  this.property = "hello";
})(jQuery, document, window);

console.log(module.property);

This allow you to create an IIFE which itself is a constructor so you get a new object based on this constructor. If you don't like the object literal based solution, this is a way to go.

Also you can take a look at AMD (using RequireJS) or CommonJS (using Node.js or Browserify) specifications which allows you to move every single module to its own file. Lots of libraries use these patterns. I prefer CommonJS and it's very simple. You have a file which represents a module and which has 3 additional predefined variables. They are exports, module and require.

// a.js
exports.property = "hello"; // Basically the same as the example above

// b.js
module.exports = function () { // Something similar to exporting a custom object
  console.log("hello");
};

// c.js
var a = require("./a"), b = require("./b"); // Loading these modules

console.log(a.property); // logs "hello"
b(); // also logs "hello"


问:
Android testing - bugs not reproducible
We have the following problem: at the end of the iteration we give our Android app to our customers to test.

Our customers report bugs that are not reproducible on our test devices.

How can we deal with this situation?

Are there any tools we can use (for example to record their actions)?

Or is it possible to remote debug on their devices?

It really comes down to this: there are so many devices and Android versions and lots of times problems appear only on specific devices (for example we had a problem with multipart SMS not being sent, only on Samsung devices).

答:
Preliminary note:

You are in need of debugging on a specific device after release, but I will also address testing before release.

One resource to consider is vendor loaner or rental programs for development partners (developer partner programs). Some provide short-term access for testing purposes affordably, perhaps even free.

Most of the hardware vendors have developer programs, which offer hardware for reduced costs or even free (e.g. Samsung, Motorola, Apple, BlackBerry (for BlackBerry Alliance Members), LG). Check them out for the devices you want/need.

There are publicly accessible 'physical' test labs that you can just walk into (or reserve time). They are usually called open device labs: starting point, Google search. Check out if there are any in your neighbourhood and what devices they have.

There's the occasional 'crowdsourced' testing community like uTest that you can ask around.

Note that there are also many on-line services for testing your apps on many devices like AppThwack, TestFlight, TestObject, TestFairy, Keynote a.k.a. DeviceAnywhere, or Xamarin test cloud that maybe have the device you want to test on.

You would also use these before releasing your app, and although these are not 'definitive' testing platforms (there's much to be said for testing on real devices), any tests helps.

Note: Useful overview article

Title: Android testing - bugs not reproducible


问:
Efficiency of self-education
Do you think being self-educated in software development is good? Please give an example of what you have learnt successfully by yourself.</p>

答:
You need to get the point you don't need hand holding.  You must be at the point where you can pick up a book, look at a help file, find a tutorial, etc. and learn the principals you need for your job.

BTW, you need this for any and every job, not just programming.  The medium of how you self-learn may be different but you must do it.

Title: Efficiency of self-education


问:
Data generation system modular design
I am trying to think of the most sensible way to design the architecture of a data generation system with several steps.

Data in the system goes through several transformations which can be divided into separate steps (from the business logic point of view).

I would like the system to keep this modular design, in such a way that each module represents a step in the data transformation.

A module's input should be the previous module's output.

What are some good ways to orchestrate this flow?

How should modules communicate with each other?

In each step, where should the input come from, and where should the output go?

Is it a good idea to use a database as the source and target of data consumption / generation for each module?

Should modules be built as separate scripts / executables which only
directly communicate with the database?

Edit:

The system will be implemented by several people. Each developer will be assigned a module. I would like the architecture to simplify the workflow by allowing each developer to work independently; and make assumptions only about the data their specific module consumes.

Edit 2:

The modules relationship is depicted below.

Modules are represented as blue boxes. Some modules depend on data generated by other modules (black arrows). Some modules need to persist data on the DB (dotted gray arrows).

答:
Pipelines are extremely common paradigm in software design. They are quite common in scripting environments (most of the shells), where each step is separate program/process and functional world, where each step is a function. You should draw inspiration from them.

What are some good ways to orchestrate this flow?
  How should modules communicate with each other?
  In each step, where should the input come from, and where should the output go?

There is usually some third party that does all of this. It ensures each part is called in right order with right data.

Is it a good idea to use a database as the source and target of data consumption / generation for each module?

I believe modules should be independent on how the intermediate data is stored. It just gets data in some common format.

Should modules be built as separate scripts / executables which only directly communicate with the database?

They should all be separate. But they should receive the data, not pull it.

One thing that comes to mind for all of this is that you have two solutions for how to transfer data :

Apply rigorous design of data structures, that are passed between modules, so all of them depend on those.

Have each module create it's own data structure and have "transformation steps" between modules, that depend on data structures of modules between which this transformation is. This is common in shells, where you use text manipulation tools to transform output of one program into input of other.

Title: Data generation system modular design


答:
"Growing balls" was mentioned, but that's mostly a problem of the manager, who has pressure from above and lets himself being talked into promises that he cannot keep. At my workplace things got improved a lot when my manager's manager, who never managed to get the results he promised, was replaced. The new manager was given a list of 10 things to achieve, and he just said "no" to seven of them. And didn't budge one bit from the seven "no's" no matter how they tried to pressure him. And then the teams under him, without ridiculous deadlines, achieved the three tasks he had accepted. Which the previous manager would have failed to do. Everyone (up and down) is really happy with him.

What bad deadline setting achieves is: Pointless stress, drop in productivity, feeling bad because everyone fails, possibly rushed and low quality products.

What you can achieve with deadlines: Change priorities so that some tasks will be finished. For example, if job A looks like it will be 90% finished, and job B looks like it will be 60% finished, you move effort from B to A so that one of them will be done within the deadline. Or reduce the scope of a job. If job A with all planned features cannot be achieved in the deadline, you reduce the features.

About estimates: If you make a best estimate for the time a task takes, and you are really, really good, then the task will take the estimated time, plus or minus some random extra time. That's why it is called a "best estimate". If you make an estimate, nobody can change that. Never allow anyone to make you change your estimates (unless they first reduce the task that is estimated). Your manager then can set targets. If these targets don't agree with the estimates, that's his fault. If you estimate "it takes three months" and he says "do it in two weeks", it's his fault if you don't finish in two weeks. It's even more his fault if he stresses you out and you don't even finish in the estimated three months.

Title: Why are deadlines always so short?