问:
Best approach for realtime sync + shared todo?
I'm implementing an app that has among other things shared todo lists. I want it to sync in real time. This has to work for "normal" single user items (e.g. user has app opened in 2 devices, doing an update in one device shows immediately in the other device) as well as the shared lists, where all the participants have to receive the update in real time.

I'm not entirely sure which kind of structure is best in order to accomplish this. I was thinking about storing a dictionary of user uuid -> socket list. When users log in or open the app while being logged in, they'll initiate a connection. Here I add an entry or update to the dictionary. When they log out or close the app, the connection is closed and I update the map accordingly. Whenever the app does an update in the server, I look up the affected users, then look up in my dictionary for possible open websockets for these users, and send the updates to them.

Another idea I had, was to associate the connections rather than with the users, with items, like e.g. the todo lists. So again I have a dictionary, but this time the key is the todo list uuid and it has an array of connections ("observers") for this list, where I broadcast wherever the list is modified. This approach is not suitable for the "single user sync" though, here the elements don't necessarily have an own identity, rather associated with the user - so I'm back to the first approach with a dictionary user -> connections.

But before I dive into more details I'd like to confirm if this is the correct train of thought. How is this normally modelled? This is rather a theory question, but in case it's relevant for something, I'm using Play Framework 2.4 / Scala.

答: This sounds like a classic publish/subscribe scenario.  I would suggest using a pub/sub design on the back-end (eg., JMS or AMQP) and using a AMQP/JMS->JavaScript framework for your browser front-end.  Here's an example: http://www.websocket.org/demos/todomvc/index.html   Very straightforward.</p>


问:
Haskell: Is it possible to convert a Num to a Float?
I need to be able to convert generic numbers (instances of Num) to a Float. I searched Hoogle for a function with the signature Num n => n -> Float, but I couldn't find any such functions (although it may be possible to compose it). I also looked over the Num typeclass, and it doesn't seem to require instances of it to supply any conversion functions that may help me.

Why do I need to do this? I created a typeclass Moveable that defines operations to move a coordinate, and allowed it to work with any instance of Num, since the only thing required to move a coordinate is +, which is defined by Num. My end goal was to use this with Gloss (a graphics library), but unfortunately, Gloss only uses Floats. That means that if I'm storing the coordinate as a Num, I'll eventually need to convert it when I try to display an object.

I'd rather not make the number type more specific to so it'll work with Gloss. Does anyone have any ideas that could help?

答:
You cannot convert arbitrary Num instances to Float because the Num class is too general to allow that.  For example, the Complex type has Num instances.  What would it mean to "convert" a complex number to a real number?  I don't think there's any accepted sense of what that would mean.

Looking through Haskell's very confusing set of numeric classes, I think I can spot this pattern: "conversion" functions are generally only provided where there is something like an injective mapping between the mathematical number sets that the types represent.  So for example, to convert an Integral instance to a real or complex number you have fromIntegral :: (Integral a, Num b) -> a -> b.  But there isn't a "conversion" function from RealFrac instances to integer types—you have to say explicitly whether you want truncate, round, ceiling or floor.

I created a typeclass Moveable that defines operations to move a coordinate, and allowed it to work with any instance of Num, since the only thing required to move a coordinate is +, which is defined by Num.

Since Complex has Num instances, your choice here means that you've admitted into your model the concept of moving coordinates by complex amounts.  Does that make sense in your application?  It sounds to me like you need to do one of the following:

Choose a narrower type for your Moveable class;

Incorporate some concept of coordinate systems and conversions into your class.

ContentLicense: CC BY-SA 3.0


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答: Re-use - I try to factor out any clever bits from previous projects, so I can use them again in future ventures. It's always worth asking yourself "could I use this again someday?"</p>

OwnerDisplayName: Nick Gotch

ContentLicense: CC BY-SA 2.5

Title: How to become a "faster" programmer?

OwnerDisplayName: Phil Jenkins


问:
Better way to transform data
Context

Imagine complicated service that provides info about bank products, fees and so on.

Imagine complicated UI that deals with it.

UI and Service data formats are changed 1-2 times/month because of active development.

Decision

To make life of UI developers easier, we transform data into format that UI developers want.

E.g. we put objects into another level in tree, add fields like brokerFee and agentFee instead of providing map of fees with their types, etc.

Current solution

We use Java code to transform Service DTO (data transfer object) into UI DTO and back.

Problem

The code doesn't look good :) It's time-consuming to maintain.

XSLT transformation is not an option because it will be even harder to maintain.

Idea

Introduce Groovy because the syntax is easier to read.

Question

What are other options?

Any patterns/libraries/approaches that can simplify data transformation code?

答:
It sounds like you want a convention-based object-to-object mapper.  There is a .NET project called automapper which does this - I would look to it for inspiration, and for what patterns you may want to implement.  The most common is simply flattening a complex object into a simpler DTO with no nested properties.

From their site, some other things to take into account:

Flattening

Projection

Configuration

Validation

Lists and Arrays

Nested Mappings

Custom Type Converters

Custom Value Resolvers

Null Substitution

Before and after map actions

Containers

Mapping Inheritance

Conditional Mapping

Open Generics

Title: Better way to transform data


答:
Practice and hard work.

You need to put the time and effort in. As you become more comfortable and confident with whatever tools your using, speed and creativity should follow.

If you want to improve any particular skill, it may also help to design exercises which will let you work specifically on that. If your slowness is in the design phase, try to find design problems to work on online. Redoing the same exercise will let you complete it faster and practice speed. I personally like TopCoder's algorithm exercises for practising sheer programming speed. They have design challenges too, but I have not tried them.

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

OwnerDisplayName: DisplacedAussie


问:
Methods with the same name
Suppose we have an interface such as

```<code>public interface anInterface
{
      public void aMethod();
}
</code>```

and a class as follows:

```<code>public class aClass
{
   public void aMethod()
   {
      //bla bla bla
   }
}
</code>```

Now I'm going to define another class such as Subclass that extends aClass and implements anInterface, as in:

```<code>public class Subclass extends aClass implements anInterface
{
   public void aMethod()
   {
      //do something
   }
}
</code>```

What does exactly aMethod() do in Subclass? Does it implement the method in anInterface? Or does it overrides the method in aClass?

What should I do in order to make aMethod() implement the method of anInterface?
Similarly, if I want it to override the method in aClass, what can I do with it?

答:
What does exactly aMethod() do in Subclass? Does it implement the
  method in anInterface? Or does it overrides the method in aClass?

It does both.

The compiler checks that Subclass fulfills its contract, being concrete: it must override all abstract methods in its hierarchy, including methods defined on interfaces. From the compiler's standpoint, an interface method and an abstract method on a regular class are the same thing: a method declaration with no definition.

The compiler sees that Subclass must have a method with the exact signature public void aMethod(). It has this method, so it satisfies the interface. This method overrides the definition in its parent class and its declaration in its parent interface.

Title: Methods with the same name


问:
windows users vs. custom
My application needs to support a "shift change" scenario. Essentially, a person is managing some assets. At the shift change, the person that was there leaves right as the replacement signs in. The assets can survive on their own for no more than three minutes. The server will re-assign the assets if they are neglected (which is not ideal). Currently, our application has a custom user system and supports a user fast-switch feature.

However, our primary customer wants to use Windows Domain users instead of our custom user system. He wants to tie our permission system to local machine user groups. It has the great advantage in that I can rip out a lot of questionable and insecure user management code, and I won't have to store passwords anymore. In my mind, that gives two options for the quick switch:

I can make our software (configurably) log off from windows on exit and auto-start when a user logs in. This has a disadvantage in that the assets are offscreen for some time period. It is easy, though.

I can keep some in-application logon form where I validate the Windows user and impersonate that user for my server requests. In a previous job I worked on a software package that took this approach. I always felt it was a bit weird having an application running as a different user than the desktop. There are some significant security concerns that go with this approach. I probably end up keeping the settings per Windows user, not per application user, etc.

Thoughts? Which path do you recommend and why? Is there some better way to do this that I didn't consider?

答:
Of the two options you have listed, the best solution really depends on how this software is used.

If the software can only every be used on the specific computer(s) that it is installed on, then option 1 is fine, as it does everything you need, and if the user has any files related to their active directory windows login, they can also access those.

If the software is supposed to be more flexible, with the possibility of it being run remotely on non-domain computers, then option 2 provides that flexibility.  This could, for example, happen if an employee needed to use the software on their home computer, allowing them to work from home.

If it's not clear where the software will be used, or both will be, consider implementing a hybrid approach where if an active directory permission is set, the user will be logged in automatically, but if this permission is not set, or the computer has not joined a domain, then it will require entering the credentials.  The Outlook email client does this on windows.

Title: windows users vs. custom


答: Really, really learn your editor.  If you use an IDE make sure you're using all the features it offers.  Get a cheat sheet to learn the keyboard shortcuts for your editor of choice. If you're using a shell set up shortcuts for commonly used directories</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: slashnick


问:
How did the gets function ever make into the standard?
We all know the dangers of gets.

It is also on the way out in C11.

That makes me wonder: how did it ever get into the standard to begin with? Weren't the problems with it obvious at the time of standardization?

答:
gets was invented at a time when there were no millions of malicious hackers trying to steal your financial data via the internet. There was no internet to speak of. People didn't put their entire personal lives on computers. Only highly paid specialists were ever supposed to have access to digital computers at all.

Briefly, the threat-countermeasure trade-off was totally different in 1972 - so different that what seems like an incredible oversight today was more like a hasty but ultimately inconsequential pragmatic choice of leaving out error checking.


问:
Is it better to check `c >= '0'` or `c >= 48`?
After a discussion with some my colleagues, I've a 'philosophical' question about how treat the char data type in Java, following the best practices.

Suppose a simple scenario (obviously this is only a very simple example in order to give a practice meaning to my question) where, given a String 's' as input, you have to count the number of numeric characters present in it.

These are the 2 possible solutions:

1)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= 48 && s.charAt(i) <= 57) {
            n++;
        }
    }
</code>```

2)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
            n++;
        }
    }
</code>```

Which of the two is more 'clean' and compliant with the Java best practices?

答:
The second example is clearly superior. The meaning of the second example is immediately obvious when you look at the code. The meaning of the first example is only obvious if you have memorized the entire ASCII table in your head.

You should distinguish between checking for a specific character, or checking for a range or class of characters.

1) Checking for a specific character.

For ordinary characters, use the character literal, e.g., if(ch=='z').... If you check against special characters like tab or line break, you should use the escapes, like if (ch=='\n').... If the character you are checking for is unusual (e.g not immediately recognizable or not available on a standard keyboard), you might use a hex character code rather than the literal character. But since a hex code is a "magic value", you would extract it to a constant and document it:

```<code>const char snowman = 0x2603; // snowman char used to detect encoding issues
...
if (ch==showman)...
</code>```

Hex codes is the standard way of specifying character codes.

2) Checking for a character class or range

You really shouldn't be doing this directly in application code, but should encapsulate it in a separate class only concerned with character classification. And you should be vary of this, since libraries already exists for this purpose, and character classification is usually more complex than you think, at least if you consider characters outside the ASCII-range.

If you are only concerned about characters in the ASCII range, you could use character literals in this library, otherwise you would probably use hex-literals. If you look at the source code for the the Java builtin character library, it also refers to character values and ranges using hexadecimal, since this is how they are specified in the Unicode standard.

Body:
The second example is clearly superior. The meaning of the second example is immediately obvious when you look at the code. The meaning of the first example is only obvious if you have memorized the entire ASCII table in your head.

You should distinguish between checking for a specific character, or checking for a range or class of characters.

1) Checking for a specific character.

For ordinary characters, use the character literal, e.g., if(ch=='z').... If you check against special characters like tab or line break, you should use the escapes, like if (ch=='\n').... If the character you are checking for is unusual (e.g not immediately recognizable or not available on a standard keyboard), you might use a hex character code rather than the literal character. But since a hex code is a "magic value", you would extract it to a constant and document it:

const char snowman = 0x2603; // snowman char used to detect encoding issues
...
if (ch==showman)...

Hex codes is the standard way of specifying character codes.

2) Checking for a character class or range

You really shouldn't be doing this directly in application code, but should encapsulate it in a separate class only concerned with character classification. And you should be vary of this, since libraries already exists for this purpose, and character classification is usually more complex than you think, at least if you consider characters outside the ASCII-range.

If you are only concerned about characters in the ASCII range, you could use character literals in this library, otherwise you would probably use hex-literals. If you look at the source code for the the Java builtin character library, it also refers to character values and ranges using hexadecimal, since this is how they are specified in the Unicode standard.


问:
Is there much difference between X86 Assembly language on Windows and Linux?
I'm a complete beginner at Assembly, and my aim is to learn as much as I can to do with Assembly to one day I can reach expert level (I know I'm way off right now, but you never know). My only problem is this: I've got two books which both teach assembly, one on a Linux and the other on Windows. They are Jeff Duntemann's Assembly Language Step By Step (the linux one) and Introduction to 80x86 Assembly Language and Computer Architecture (the windows version). If I want to get the best out of assembly, should I do this on linux and windows? Also, is the syntax the same on Windows and Linux or will I have teach my self again when learning on the other OS( which is my main concern, I want to be able to use assembly on windows and linux).</p>

答:
The one major difference between coding in ASM on Win/Linux/OSX is the calling convention. There isn't one more difficult to use than the other, they're just different. You also need to be careful about the register that need to be preserved between calls.

WINDOWS: RCX, RDX, R8, R9

The Microsoft x64 calling convention is followed on Windows and
  pre-boot UEFI (for long mode on x86-64). It uses registers RCX, RDX,
  R8, R9 for the first four integer or pointer arguments (in that
  order), and XMM0, XMM1, XMM2, XMM3 are used for floating point
  arguments. Additional arguments are pushed onto the stack (right to
  left). Integer return values (similar to x86) are returned in RAX if
  64 bits or less. Floating point return values are returned in XMM0.
  Parameters less than 64 bits long are not zero extended; the high bits
  are not zeroed.

LINUX/OSX: RDI, RSI, RDX, RCX, R8, R9

The calling convention of the System V AMD64 ABI is followed on
  Solaris, Linux, FreeBSD, OS X, and other UNIX-like or POSIX-compliant
  operating systems. The first six integer or pointer arguments are
  passed in registers RDI, RSI, RDX, RCX, R8, and R9, while XMM0, XMM1,
  XMM2, XMM3, XMM4, XMM5, XMM6 and XMM7 are used for floating point
  arguments. For system calls, R10 is used instead of RCX. As in the
  Microsoft x64 calling convention, additional arguments are passed on
  the stack and the return value is stored in RAX.

TOOLS :
You'll find pretty much the same tools on Windows & Linux.

My personal opinion :

FASM & NASM are awesome :)

I often use Purebasic, it's a closed-source commercial (cheap, with a freeware limited version) basic that produce nice readable/commented FASM code and accept Inline Assembler. It doesn't produce the fasted code ever, but it's a tool i like. You can do without it of course, and just write pure ASM from scratch.

DON'T BOTHER with 386, jump to x86_64 ASM. Much more instructions (beware : MMX/SSE packed instruction are weird, (very?) hard to use) and much much more registers (awesome!) !

Hardcore option : Install BOCHS or QEMU (i use QEMU) and start writing ASM without operating system. Start with the MBR, then bootloader Stage 1, Stage2, a kernel, and so on... Feel free to take a look at my heavily documented MBR/Bootloader (functional but incomplete) https://github.com/ker2x/zymology/tree/master/bootloader/Oak64/src if you're in the mood :)


答: Knowing your IDE and framework well. Having to turn to Google for every little thing takes time.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: Mike Hall


问:
Hide, obfuscate or otherwise prevent the harvesting of email addresses
I am developing a public repository webapp for my organization.

It will be public webapp, exposed to the internet. All people and organisational units can be queried and its contact data will be displayed. It is developed as a single page app against a REST back-end. There will also probably be a mobile front-end in the future.

One requirement is that people's emails are visible, and are clickable links with the mailto:email@so.com href attribute, so users can click on the address to quickly start writing an email.

On the other hand, I want to make email harvesting difficult for spammers (I know that with the above requirement, it will always be possible to ultimately get the email adresses but I don't want it to be extra easy). So I don't want to expose the emails in clear text in my API.

The previous version of this app used server-generated text-to-image to show the address, and then the onclick handler used an AJAX call to get the actual address from the server (based on the ID of the person), then activate the "mailto" link.

It does not seem so good to generate one or two extra server calls for each person displayed, especially when displaying a search results list. I am thinking I can probably do better. For example, I could just include the email field in my API, but obfuscate/encrypt it. The app (or any future client made by us such as a mobile app) would know how to decode the email address.

Is there a better way to do this?

答:
Don't overthink things, the obvious way (render image instead of text) is exactly the right thing to do here.

Nowadays, any time delay or processing cost involved in an extra server call wil be negligible compared to the kind of time it takes a user to move a mouse and perform a click in the first place. (From the viewpoint of a computer, people move in ultra-ultra-slow motion.)


问:
Where to put very specialised functions which heavily use one class?
I have a class which is centred around lower-level methods, to make this class much more useful it would be great to put some middle or higher level methods (i.e. methods which make a series of calls to the lower-level methods to do something that an end user may want to do).

I could add the methods to the original class, but the class will get very bloated.

I could write a module of just functions, but they would always need that class an argument.

I could inherit and make a new class: MoreSpecificClass.

What do you guys like best and why?

(I code in python)

答:
First thing I would do is figure out which methods your end user code will require. I would then create an abstract class containing all these methods as abstract methods. This means your user code now depends upon an abstract class which is good because it decouples it from how the methods are implemented and allows you to easily stub out these methods for testing.

Then create a class which implements all these methods and also imports the class containing your low-level code. These methods will make calls to the low level ones. Now if your low=level code changes it wont affect your user code directly, it will just mean you need to update the class implementing the abstract interface.

Then when you build your program your user code takes the abstract class in its constructor and makes all calls through it. This is a form of dependency injection and is a useful tool for decoupling your code.


问:
Why would I not need an ORM in a functional language like Scala?
I'm wondering if I can switch from Java to Scala in a Spring + Hibernate project to take advantage of some Scala features such as pattern matching, Option and what it seems to me a cleaner syntax in general. I've been looking for the ORM by default in the Scala ecosystem and I've found thinks like Activate (but mostly I try to find if Hibernate can be used with Scala). Searching for this I've read this in the Play documentation about JPA + Scala.

But the most important point is: do you really need a Relationnal to
  Objects mapper when you have the power of a functional language?
  Probably not. JPA is a convenient way to abstract the Java’s lack of
  power in data transformation, but it really feels wrong when you start
  to use it from Scala.

I don't have a deep understanding of how to use functional programming to create a complete application (that's why I intend to use Scala so that I can understand this incrementally, since it combines OO + Functional), so I can't figure out why I would not need an ORM with a functional language and what would be the functional approach to tackling persistence of the domain model.

A DDD approach for the business logic still makes sense with Scala, doesn't it?

答:
It's kind of hard to explain until you've done a lot of functional programming.  In object-oriented programming, your data is sort of stuck in one object and stays there.  That object gets passed around a bit, and modified quite a bit, but you're usually fundamentally working with the same "identity" over the lifetime of that data.

ORMs are generally designed around that paradigm.  You retrieve some data from the database, munge it into an object, potentially modify it a bunch, and when you're done, you still have the same object you can write back to the database.

Functional programming works differently.  Your data doesn't maintain a single identity over its lifetime.  It gets split up, copied, shared, and transformed.  It sort of flows through a bunch of functions, then eventually gets reassembled into the output form you need.  For any database API to feel natural in a functional language, it has to take that into account, and JPA doesn't.

OwnerDisplayName: gabrielgiussi

OwnerDisplayName: Karl Bielefeldt


答:
Keep it simple.

If you use TDD, you should follow "red, green, refactor":

Write a failing test (red). (Often for functionality your code does not yet have.)

Commit horrible coding crimes to get your tests to pass (green). Hardcode if necessary.

Refactor, probably breaking tests for a short while, but overall improving the design.

Title: How to become a "faster" programmer?

OwnerDisplayName: bryanbcook


答:
Well, one thing that's important to do whenever we have a discussion like this is to clearly distinguish between object relational mappers ("ORM") and database abstraction layers.  An ORM is a kind of database abstraction layer, but not all database abstraction layers are ORMs.  One good tool to study to grasp this is Python's popular SQLAlchemy library, which bills itself as a "SQL toolkit and Object Relational Mapper" (my boldface), with the idea that these are different things.  As they put it in their key features page:

No ORM Required

SQLAlchemy consists of two distinct components, known as the Core and the ORM. The Core is itself a fully featured SQL abstraction toolkit, providing a smooth layer of abstraction over a wide variety of DBAPI implementations and behaviors, as well as a SQL Expression Language which allows expression of the SQL language via generative Python expressions. A schema representation system that can both emit DDL statements as well as introspect existing schemas, and a type system that allows any mapping of Python types to database types, rounds out the system. The Object Relational Mapper is then an optional package which builds upon the Core.

The front page describes the ORM like this:

SQLAlchemy is most famous for its object-relational mapper (ORM), an optional component that provides the data mapper pattern, where classes can be mapped to the database in open ended, multiple ways - allowing the object model and database schema to develop in a cleanly decoupled way from the beginning.

The key idea of an ORM is to try and bridge the famous object-relational impedance mismatch.  This means defining relationships between user-defined classes to tables in a database schema and providing automatic "save" and "load" operations for your application's classes.

In contrast, non-ORM database abstraction layers tend to be more committed to the relational data model and to SQL, and not at all to object-orientation.  So instead of featuring "mappings" between tables and classes and hiding the database schema from the programmer, they tend to expose the database to the programmer but with better APIs and abstractions.  For example, SQL query builders allow you to generate complex SQL queries programmatically, without string manipulation, like this (an example from the jOOQ library for Java):

```<code>// Typesafely execute the SQL statement directly with jOOQ
Result<Record3<String, String, String>> result =
    create.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
          .from(BOOK)
          .join(AUTHOR)
          .on(BOOK.AUTHOR_ID.equal(AUTHOR.ID))
          .where(BOOK.PUBLISHED_IN.equal(1948))
          .fetch();
</code>```

Now, the Play framework doesn't seem to be 100% in league with what I just described, but their argument seems to be in this general space: work with the relational model directly instead of translating it to classes and back from them.

The jOOQ library is worth studying as a counterpoint to ORMs.  They also have some relevant blog entries that are worth a read:

http://blog.jooq.org/2015/03/24/jooq-vs-hibernate-when-to-choose-which/

http://blog.jooq.org/2014/04/11/java-8-friday-no-more-need-for-orms/

Title: Why would I not need an ORM in a functional language like Scala?

Body:
I'm wondering if I can switch from Java to Scala in a Spring + Hibernate project to take advantage of some Scala features such as pattern matching, Option and what it seems to me a cleaner syntax in general. I've been looking for the ORM by default in the Scala ecosystem and I've found thinks like Activate (but mostly I try to find if Hibernate can be used with Scala). Searching for this I've read this in the Play documentation about JPA + Scala.

But the most important point is: do you really need a Relationnal to
  Objects mapper when you have the power of a functional language?
  Probably not. JPA is a convenient way to abstract the Java’s lack of
  power in data transformation, but it really feels wrong when you start
  to use it from Scala.

I don't have a deep understanding of how to use functional programming to create a complete application (that's why I intend to use Scala so that I can understand this incrementally, since it combines OO + Functional), so I can't figure out why I would not need an ORM with a functional language and what would be the functional approach to tackling persistence of the domain model.

A DDD approach for the business logic still makes sense with Scala, doesn't it?

Body:
Well, one thing that's important to do whenever we have a discussion like this is to clearly distinguish between object relational mappers ("ORM") and database abstraction layers.  An ORM is a kind of database abstraction layer, but not all database abstraction layers are ORMs.  One good tool to study to grasp this is Python's popular SQLAlchemy library, which bills itself as a "SQL toolkit and Object Relational Mapper" (my boldface), with the idea that these are different things.  As they put it in their key features page:

No ORM Required

SQLAlchemy consists of two distinct components, known as the Core and the ORM. The Core is itself a fully featured SQL abstraction toolkit, providing a smooth layer of abstraction over a wide variety of DBAPI implementations and behaviors, as well as a SQL Expression Language which allows expression of the SQL language via generative Python expressions. A schema representation system that can both emit DDL statements as well as introspect existing schemas, and a type system that allows any mapping of Python types to database types, rounds out the system. The Object Relational Mapper is then an optional package which builds upon the Core.

The front page describes the ORM like this:

SQLAlchemy is most famous for its object-relational mapper (ORM), an optional component that provides the data mapper pattern, where classes can be mapped to the database in open ended, multiple ways - allowing the object model and database schema to develop in a cleanly decoupled way from the beginning.

The key idea of an ORM is to try and bridge the famous object-relational impedance mismatch.  This means defining relationships between user-defined classes to tables in a database schema and providing automatic "save" and "load" operations for your application's classes.

In contrast, non-ORM database abstraction layers tend to be more committed to the relational data model and to SQL, and not at all to object-orientation.  So instead of featuring "mappings" between tables and classes and hiding the database schema from the programmer, they tend to expose the database to the programmer but with better APIs and abstractions.  For example, SQL query builders allow you to generate complex SQL queries programmatically, without string manipulation, like this (an example from the jOOQ library for Java):

// Typesafely execute the SQL statement directly with jOOQ
Result<Record3<String, String, String>> result =
    create.select(BOOK.TITLE, AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)
          .from(BOOK)
          .join(AUTHOR)
          .on(BOOK.AUTHOR_ID.equal(AUTHOR.ID))
          .where(BOOK.PUBLISHED_IN.equal(1948))
          .fetch();

Now, the Play framework doesn't seem to be 100% in league with what I just described, but their argument seems to be in this general space: work with the relational model directly instead of translating it to classes and back from them.

The jOOQ library is worth studying as a counterpoint to ORMs.  They also have some relevant blog entries that are worth a read:

http://blog.jooq.org/2015/03/24/jooq-vs-hibernate-when-to-choose-which/

http://blog.jooq.org/2014/04/11/java-8-friday-no-more-need-for-orms/

OwnerDisplayName: sacundim


答:
If using a subscription based cloud service is an option for your use case you should have a look at Realtime Cloud Storage (the company I work for).

It's a data backend (powered by AWS DynamoDB) with scalable real-time data-sync features. More at http://framework.realtime.co/storage/

We also have an on-line todo demo written in JavaScript at http://storage-public.realtime.co/samples/todo-lbl/index.html#/

Title: Best approach for realtime sync + shared todo?

Body:
I'm implementing an app that has among other things shared todo lists. I want it to sync in real time. This has to work for "normal" single user items (e.g. user has app opened in 2 devices, doing an update in one device shows immediately in the other device) as well as the shared lists, where all the participants have to receive the update in real time.

I'm not entirely sure which kind of structure is best in order to accomplish this. I was thinking about storing a dictionary of user uuid -> socket list. When users log in or open the app while being logged in, they'll initiate a connection. Here I add an entry or update to the dictionary. When they log out or close the app, the connection is closed and I update the map accordingly. Whenever the app does an update in the server, I look up the affected users, then look up in my dictionary for possible open websockets for these users, and send the updates to them.

Another idea I had, was to associate the connections rather than with the users, with items, like e.g. the todo lists. So again I have a dictionary, but this time the key is the todo list uuid and it has an array of connections ("observers") for this list, where I broadcast wherever the list is modified. This approach is not suitable for the "single user sync" though, here the elements don't necessarily have an own identity, rather associated with the user - so I'm back to the first approach with a dictionary user -> connections.

But before I dive into more details I'd like to confirm if this is the correct train of thought. How is this normally modelled? This is rather a theory question, but in case it's relevant for something, I'm using Play Framework 2.4 / Scala.


答:
SteveChallender's answer is good, and I upvoted it.  (Remember, upvoting stands for "this answer is useful".)  However, in your case it might represent a bit of over-engineering.  You are the one who really knows, and therefore the one who judges whether it is so, I am simply pointing out the possibility that it might be so.

Here is my input on the three possibilities that you listed:

I could add the methods to the original class, but the class will get very bloated.

This could very possibly be your best choice. Lately I have been noticing that many programmers are totally frightened by sheer line counts.  Someone reviewing my code once called a 250-line class of mine "awfully long".  The poor guy has not seen some 2500-line classes that I have.  Here is the thing: if the class is really doing just one thing, and if there is no internal structure in it, (no disjoint sets of internal state used by different groups of methods,) if the methods are simply doing stuff invoking other methods, then they truly all belong to the same class.  It is just a fact of life.  It is a huge mistake to add unnecessary additional structure to your system's design only in order to reduce the number of lines of an otherwise perfectly fine class, just because the number of lines in that class exceeds some blind preconceptions about what a good number of lines should be.  Remember, "Things should be as simple as possible, but not simpler." (A. Einstein.) And that's because if you try and make them "simpler than possible" then you are practically guaranteed that you will actually end up making them more complicated.

I could write a module of just functions, but they would always need that class an argument.

Yes, that would not be a very smart thing to do.  A large number of functions which all accept a specific class as an argument is in fact a large number of functions screaming "put us in that class!" or at worst, "put us in a class, and make that object a member of that class, so we know where to find it!"

I could inherit and make a new class: MoreSpecificClass.

Making functionality available to different subsets of code is one of the least legitimate reasons for using inheritance.  You should use inheritance if your MoreSpecificClass has an "is a" relationship with your LessSpecificClass. Will it have such a relationship?  Will you ever have a function which accepts "LessSpecificClass" as an argument and be in the need to pass a "MoreSpecificClass" instead? I doubt that you are planning to do such a thing, so I doubt that inheritance is suitable here.

Title: Where to put very specialised functions which heavily use one class?

Body:
I have a class which is centred around lower-level methods, to make this class much more useful it would be great to put some middle or higher level methods (i.e. methods which make a series of calls to the lower-level methods to do something that an end user may want to do).

I could add the methods to the original class, but the class will get very bloated.

I could write a module of just functions, but they would always need that class an argument.

I could inherit and make a new class: MoreSpecificClass.

What do you guys like best and why?

(I code in python)


问:
Sorting array according to a formula
I need to sort the values according to the following problem:

For every n, determine the triples (i,j,k) that satisfies i+j+k=n, then sort the triples (for every n) with respect to the value of the formula (4*i+5*j+4*k+1) in ascending order. Here is the rough pseudocode:

```<code>for n in range(3,N+1):
   for i in range(1,n-1):
        for j in range(1,n-1):
            for k in range(1,n-1):
                 if(i+j+k)==n:
                    [sort triples in ascending order wrt to the value of (4*i+5*j+4*k+1)]
</code>```

For now, I can only print the triples that satisfy i+j+k=n.

Is there a way to do the sorting inside the n loop? Or should I store them in an array then bubble sort later?

答:
For this precise case, (4*i+5*j+4*k+1) = 4*n+j+1.  Since n is a constant you need to sort it by j.  Or just use j for your outer loop (after n).

Also, you can compute k directly from i and j

```<code>for n in range(3,N+1):
   for j in range(1,n-1):
        for i in range(1,n-1):
            k = (n-i-j)
            if (1<=k && k<=n):
                 [print triplet (i,j,k)]
</code>```

Title: Sorting array according to a formula

Body:
For this precise case, (4*i+5*j+4*k+1) = 4*n+j+1.  Since n is a constant you need to sort it by j.  Or just use j for your outer loop (after n).

Also, you can compute k directly from i and j

for n in range(3,N+1):
   for j in range(1,n-1):
        for i in range(1,n-1):
            k = (n-i-j)
            if (1<=k && k<=n):
                 [print triplet (i,j,k)]


答: Learn your development IDE in and out. Learn the shortcut keys. Learn to use the mouse less. I find that this saves much time for me.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: Devtron


问:
Relation between BDD and TDD
What is the relation of BDD and TDD?

From what I understood BDD adds two main things over TDD: tests naming (ensure/should) and acceptance tests. Should I follow TDD during development by BDD? If yes, should my TDD unit tests be named in the same ensure/should style?

答:
My understanding of it:

BDD started as a rebranding of TDD to make the focus on behaviour clearer.

It gives more formal support (DSL and tooling) for a focus on behaviour and executable specifications.

BDD can now be seen as a superset of TDD,.  It has grown over-time to encompass more of the requirements elicitation side of things, but still the development process side is a core part of it.

So to address the TDD done right part of BDD.  BDD started as a change in language of TDD to make the intention of the process clear.  Dan North's introductory article on BDD explains why focusing on the word behaviour rather than test is useful - it helps confirm that you are not just building the software right, you are also building the right software.  This was always part of a good TDD approach, but Dan codified it a bit into BDD.

What I think BDD makes a bit more explicit than TDD, or at least formalises and provides tool support for, is this two-cycle / double loop / zoom-in zoom-out  / outside-in approach.   You first describe the expected behaviour of the feature (the outside loop), then zoom-in to the inner loop to deal with the low-level specifications.

From http://www.metesreau.com/ncraft-workshop/

Gherkin in conjunction with tools like Cucumber and SpecFlow provide a way of writing those high-level feature specifications and then linking them in to code that executes the application code.  I would argue that this is where BDD might 'feel' different from TDD, but it really still is doing the same thing, just with some added tool support and a DSL.  Somewhat closer to 'traditional' TDD is using tools like rspec, nspec, spock.  These feel a little more like the same process you'd do in 'traditional' TDD but with more behaviour-focused language.

In BDD in Action by John Ferguson Smart (highly recommended), he advocates for a double loop approach, starting with something like jBehave at the outer level executable specifications, then dropping into a tool like Spock for the low-level specifications.

BDD brings the concept of test-driven closer to the business stakeholders.  Gherkin is designed to be business readable, and the idea of 'living documentation', i.e. automatically produced progress reports from your executable specifications is about giving feedback to the stakeholders.

Another part of BDD now, which is where it genuinely becomes something that incorporates TDD as part of a larger process, are the requirements elicitation bits and pieces.  Ideas like Feature Injection, Impact Mapping, and Real Options are part of this side.

For the canonical answer on this, it might be best to go to Dan North again.    If your team is all developers, then BDD = TDD.  If your team involves a whole range of stakeholders, BDD is closer to XP, with TDD being one part of it.

Title: Relation between BDD and TDD


答: Why not use an image as stated above, and include a (lightly) encrypted email address for each image, along with a local Javascript function to resolve the obfuscated email upon click?  That way everything stays single-trip, but most spam harvesters aren't going to be hooking into the event and looking for a process path for a result, they're just going to read the tag and hope it's valid.  Simple and effective, no?  Not the cure all end all, but it ought to do.</p>

Title: Hide, obfuscate or otherwise prevent the harvesting of email addresses

Body:
I am developing a public repository webapp for my organization.

It will be public webapp, exposed to the internet. All people and organisational units can be queried and its contact data will be displayed. It is developed as a single page app against a REST back-end. There will also probably be a mobile front-end in the future.

One requirement is that people's emails are visible, and are clickable links with the mailto:email@so.com href attribute, so users can click on the address to quickly start writing an email.

On the other hand, I want to make email harvesting difficult for spammers (I know that with the above requirement, it will always be possible to ultimately get the email adresses but I don't want it to be extra easy). So I don't want to expose the emails in clear text in my API.

The previous version of this app used server-generated text-to-image to show the address, and then the onclick handler used an AJAX call to get the actual address from the server (based on the ID of the person), then activate the "mailto" link.

It does not seem so good to generate one or two extra server calls for each person displayed, especially when displaying a search results list. I am thinking I can probably do better. For example, I could just include the email field in my API, but obfuscate/encrypt it. The app (or any future client made by us such as a mobile app) would know how to decode the email address.

Is there a better way to do this?


问:
How can I estimate the lifespan of a line of code?
I'm trying to figure out a way to analyze code longevity in open source projects: that is, how long a specific line of code is active and in use.

My current thinking is that a line of code's lifespan begins when it is first committed, and ends when one of the following occurs:

It's edited or deleted,

Excluded from builds,

No code within its build is maintained for some period of time (say, a year).

NOTE: As clarification on why an "edit" is being counted as "death", edited lines would be counted as a "new" generation, or line of code. Also, unless there's an easy way to do this, there would be no accounting for the longevity of a lineage, or descent from an ancestor.

What else would determine a line of code's lifespan?

答:
I don't think there is an answer for that. It's highly project dependant. Some are more stable over the years, others are more volatile/refactored/evolving over the years.

Moreover, it's difficult to measure. Is an editted line really the end of it's lifespan? What about only a cosmetic change like reformatting the codebase with tabs or spaces? IMHO that doesn't count as renewed codebase, but it would according to your criteria.

That said, I think a good chunk of the LOCs live forever.

The reason is simple: it's way easier to add new code rather than to remove some. Especially when the system is complex and grown over the years. It then quickly comes to a point where it's "risky" to remove or change non-trivial code. It could introduce bugs, break compatibility, introduce a butterfly effect of changes... So I think, the bigger the codebase becomes, the older it is, the more the LOCs are going to stay.

Moreover, only good programmers tend to cleanup codebases and reduce the lines. All others tend to pile up the LOCs. And so far, the latter are winning by far. ;)


答: Do it right, the best way, first time.  If that means you have to stop and think about it for a while before you start, then do it.  Works 90% of the time.</p>

Title: How to become a "faster" programmer?


答:
First, let me say that the image is a good solution, and it does not require any extra roundtrips to the server while displaying search results: once generated, the image can be saved in an image file on the filesystem of the server, and served as a plain . This means that the server will essentially be caching the images, recomputing them only in the event that an email address has changed. Extra roundtrips to the server will only be required when the user clicks on an email address image, but clicking is an operation performed in human time, and therefore represents negligible overhead.

One slight problem with this approach is that spammers may be using optical character recognition technology.  One way to account for this possibility would be to make the rendered email addresses difficult to read, sort of like a captcha, but you will never have any metric telling you how successful you were in this.

Other approaches:

Require authentication.

Make the webpages of your public repository webapp visible to all visitors, but hide the email addresses. When a visitor clicks on (or hovers over) a hidden email address, inform them that they have to register in order to view that information. In the registration process, require a captcha. The logic behind this:

It is only fair that you can see our email addresses if you first let us know yours, right?

Note that you can even use this approach in addition to serving email addresses as clickable images, for added security.

Also note that you can use this approach to protect a lot more information than just email addresses.  (What if there is a need to also protect phone numbers later?)

Use additional anti-harvesting measures.

One approach commonly used is to require that clients use cookies, so as to be able to identify each client, and then keep track of requests received by the server from a specific client, and if the client sends too many requests too fast, then blacklist them.  Normally, blacklisting means denying any service whatsoever, but in your case, blacklisting could simply mean that from that moment on you don't show them any more email addresses, or that from that moment on you start showing them images instead of email addresses.

Note that this is a generally useful thing to have, which may prevent various different kinds of abuse, and you might want to implement it regardless of what you end up doing specifically for the email addresses.

Implement "we'll call you back"

If you really want to avoid authentication, then instead of displaying email addresses, you can have a "contact" field, which, when clicked, pops up a dialog which asks the visitor to enter their email address, (probably along with a captcha,) and sends the visitor an email message to which the visitor may reply.

Body:
First, let me say that the image is a good solution, and it does not require any extra roundtrips to the server while displaying search results: once generated, the image can be saved in an image file on the filesystem of the server, and served as a plain <img src="user337567.png"/>. This means that the server will essentially be caching the images, recomputing them only in the event that an email address has changed. Extra roundtrips to the server will only be required when the user clicks on an email address image, but clicking is an operation performed in human time, and therefore represents negligible overhead.

One slight problem with this approach is that spammers may be using optical character recognition technology.  One way to account for this possibility would be to make the rendered email addresses difficult to read, sort of like a captcha, but you will never have any metric telling you how successful you were in this.

Other approaches:

Require authentication.

Make the webpages of your public repository webapp visible to all visitors, but hide the email addresses. When a visitor clicks on (or hovers over) a hidden email address, inform them that they have to register in order to view that information. In the registration process, require a captcha. The logic behind this:

It is only fair that you can see our email addresses if you first let us know yours, right?

Note that you can even use this approach in addition to serving email addresses as clickable images, for added security.

Also note that you can use this approach to protect a lot more information than just email addresses.  (What if there is a need to also protect phone numbers later?)

Use additional anti-harvesting measures.

One approach commonly used is to require that clients use cookies, so as to be able to identify each client, and then keep track of requests received by the server from a specific client, and if the client sends too many requests too fast, then blacklist them.  Normally, blacklisting means denying any service whatsoever, but in your case, blacklisting could simply mean that from that moment on you don't show them any more email addresses, or that from that moment on you start showing them images instead of email addresses.

Note that this is a generally useful thing to have, which may prevent various different kinds of abuse, and you might want to implement it regardless of what you end up doing specifically for the email addresses.

Implement "we'll call you back"

If you really want to avoid authentication, then instead of displaying email addresses, you can have a "contact" field, which, when clicked, pops up a dialog which asks the visitor to enter their email address, (probably along with a captcha,) and sends the visitor an email message to which the visitor may reply.


问:
Who does what in a Single Page Application?
My development background is in ASP .NET webforms. I've been reading various SPA tutorials but they always get into the weeds about specific javascript libraries.

I'm just trying to understand what happens in an SPA with a .NET middle tier.

Specifically:

Does the domain model exist both in .NET and javascript?

Is the javascript model more of a view model than a complete domain model?

Does this eliminate the need for views in the context of ASP MVC? ie. Does making an SPA basically turn ASP MVC into ASP MC?

Does the .NET layer only send data (JSON/XML) to the client? No markup?

Does all the ASP MVC routing configuration become largely irrelevant? Is all the routing handled client side?

答:
So, I'm more experienced in PHP and Python but my answers should be valid for ASP .NET too, seen that your questions are more about the MVC structure rather than the language / framework itself.

First of all, the choice of the javascript library may be crucial to answer your questions. For instance, if you choose the full MeteorJS stack (where models are shared between the server and the client) or just a front-end library like Angular or React (or a combination of both).

Does the domain model exist both in .NET and javascript?

It might: depends on the library. The data is normally received as a JSON object via an XMLHttp call (or websocket, for a Meteor App) or directly accessed from the local storage. Implementing a model could be useful to keep your code clean (in Typescript you could use an interface) but for handling CRUD operations it really depends on the JS library of your choice.

Is the javascript model more of a view model than a complete domain model?

In a SPA you normally have Controllers (or "components", or "directives"), not view models. Again, it really depends on the JS framework / library. In the latest Angular 2.0 iteration the component is both a view and a controller. For more infos: https://www.youtube.com/watch?v=g9GgByAy80s

Does this eliminate the need for views in the context of ASP MVC? ie. Does making an SPA basically turn ASP MVC into ASP MC?

Yes, if you plan to use ASP as a RESTful API endpoint you still need controllers for routing and Models for CRUD: ideally, the "View" is just a JSON document.

Does the .NET layer only send data (JSON/XML) to the client?

Yes, but it should also be able to handle requests for CRUD operations (GET, POST, UPDATE, DELETE for REST, others for the DDP protocol)

No markup?

What kind of markup do you want to send?

Does all the ASP MVC routing configuration become largely irrelevant? Is all the routing handled client side?

As stated before, you'll still need routing to handle REST / DDP business logic. Everything else (like URL routing that the user can interact with in the browser bar) is managed by the SPA (and of course, the usage varies depending on your library choice)


答:
Some ideas...

Avoid gold plating - do only what is asked of you (in terms of requirements)

Understand business requirements and do it right the first time

Thoroughly understand your environment and tools

Become a fantastic typist, use keyboard shortcuts instead of the mouse

Take an iterative approach and build in sanity checks to ensure you are on the right path

Don't reinvent the wheel, consider reusing past work and the work of others

Eliminate distractions, don't keep checking email, looking outside, talking to coworkers, etc.

Don't overwork yourself - recognize when you need to take breaks

Title: How to become a "faster" programmer?

OwnerDisplayName: Mayo


问:
Merits of copy-on-write semantics
I am wondering what possible merits does copy-on-write have? Naturally, I don't expect personal opinions, but real-world practical scenarios where it can be technically and practically beneficial in a tangible way. And by tangible I mean something more than saving you the typing of a & character.

To clarify, this question is in the context of datatypes, where assignment or copy construction creates an implicit shallow copy, but modifications to it creates an implicit deep copy and applies the changes to it instead of the original object.

The reason I am asking is I don't seem to find any merits of having COW as a default implicit behavior. I use Qt, which has COW implemented for a lot of the datatypes, practically all which have some underlying dynamically allocated storage. But how does it really benefit the user?

An example:

```<code>QString s("some text");
QString s1 = s; // now both s and s1 internally use the same resource

qDebug() << s1; // const operation, nothing changes
s1[o] = z; // s1 "detaches" from s, allocates new storage and modifies first character
           // s is still "some text"
</code>```

What do we win by using COW in this example?

If all we intend to do is use const operations, s1 is redundant, might as well use s.

If we intend to change the value, then COW only delays the resource copy until the first non-const operation, at the (albeit minimal) cost of incrementing the ref count for the implicit sharing and detaching from the shared storage. It does look like all the overhead involved in COW is pointless.

It is not much different in the context of parameter passing - if you don't intend to modify the value, pass as const reference, if you do want to modify, you either make an implicit deep copy if you don't want to modify the original object, or pass by reference if you want to modify it. Again COW seems like needless overhead that doesn't achieve anything, and only adds a limitation that you cannot modify the original value even if you want to, as any change will detach from the original object.

So depending on whether you know about COW or are oblivious to it, it may either result in code with obscure intent and needless overhead, or completely confusing behavior which doesn't match the expectations and leaves you scratching your head.

To me it seems that there are more efficient and more readable solutions whether you want to avoid an unnecessary deep copy, or you intend to make one. So where is the practical benefit from COW? I assume there must be some benefit since in it used in such a popular and powerful framework.

Furthermore, from what I've read, COW is now explicitly forbidden in the C++ standard library. Don't know whether the con's I see in it have something to do with it, but either way, there must be a reason for this.

答:
Copy on write is used in situations where you very often will create a copy of the object and not modify it.  In those situations, it pays for itself.

As you mentioned, you can pass a const object, and in many cases that is sufficient.  However, const only guarantees that the caller can't mutate it (unless they const_cast, of course).  It does not handle multithreading cases and it does not handle cases where there are callbacks (which might mutate the original object).  Passing a COW object by value puts the challenges of managing these details on the API developer, rather than the API user.

The new rules for C+11 forbid COW for std::string in particular.   Iterators on a string must be invalidated if the backing buffer is detached.  If the iterator was being implemented as a char* (As opposed to a string* and an index), this iterators are no longer valid.  The C++ community had to decide how often iterators could be invalidated, and the decision was that operator[] should not be one of those cases.  operator[] on a std::string returns a char&, which may be modified.  Thus, operator[] would need to detach the string, invalidating iterators.  This was deemed to be a poor trade, and unlike functions like end() and cend(), there's no way to ask for the const version of operator[] short of const casting the string. (related).

COW is still alive and well outside of the STL.  In particular, I have found it very useful in cases where it is unreasonable for a user of my APIs to expect that there's some heavyweight object behind what appears to be a very lightweight object.  I may wish to use COW in the background to ensure they never have to be concerned with such implementation details.

Title: Merits of copy-on-write semantics


答:
In scala it is still useful to map database tables to objects, and there are several ways of doing it.

One popular framework in the world of Scala is slick. It is not an ORM, because it does less (namely, it doesn't fetch relationships without being told to do joins explicitly).

So you still map objects to database rows, but your objects are immutable, (hence no state-flushing) and you explicitly execute queries using a monadic DSL. The result is you get a lot of the "good" parts of an ORM without the issues around mutability, and unpredictable N+1 problems.

One should note that people have gotten great success using much thinner libraries, like anorm or straight JDBC too, using functional techniques to keep code beautiful.

One fantastic library that applies functional techniques on top of JDBC is also doobie.

So you have a lot of choices for database access, but Hibernate (which seems to be the de-facto ORM) isn't one of the best ones, due being biased towards mutability.


答:
The technique that I use is evolutionary prototyping

You can google for more info - but if the need is to produce something quickly, it's about the only way to go. Plus, it has the benefit that when the users says that he likes it, your'e done (... and can start doing the documentation).

Title: How to become a "faster" programmer?

OwnerDisplayName: slashmais


问:
Should a generic vector class allow non-finite doubles as values?
I am currently writing an immutable multipurpose vector class in Java that essentially wraps a double[]. The class will be part of a game library, used to calculate entity positions, physics, pixel coordinates etc. I aim to make them also usable for other (non-game related) calculations.

The vector class provides basic operations such as (a and b are vectors):

a.length() (returning the length of the vector in Euclidean space)

a.add(b), a.scale(b) (adding or multiplying all vector components)

a.dot(b), a.cross(b) (calculating dot and cross product of a and b).

I am debating whether I should allow NaN, positive and negative infinity as vector values and whether I should distinguish between +0 and -0. Are there any reasons to why allowing non-finite doubles should be allowed? Is it even practical to implement operations for these methods - how should e.g. length() and scale(..) behave?

Another important concern I have are the methods a.hashCode() and a.equals(b). Should this be true:

```<code>new Vector(+0D, +0D, +0D).equals(new Vector(-0D, -0D, -0D));
</code>```

Considering that

```<code>Arrays.equals(new double[] { +0D, +0D, +0D }, new double[] { -0D, -0D, -0D }) == false
</code>```

答:
How would you handle arithmetic operations that would return NaN? Your options are to either:

allow returning non-finite values

make sure that those operations throw exceptions, or

let them return null.

Number one reminds me of the null object pattern, and number three sounds like sacrilege if you're trying to make robust code without checking for null everywhere. Number two sounds feasible but exception handling sounds like clutter. It's up to you, but you'll be creating NaN's no matter what.


问:
Modern frameworks method conventions
I've been noticing that modern frameworks tend to have this kind of code style:

expect(6 - 4).toBe(2)

this can be rephrased as: assert(6-4, 2)

Yet the former is much more readable.

I would like to read more about this "style" of coding, but I have no idea what to search for. Does this convention have a name?

Thanks.

答:
It's called a fluent interface.

Some people may call it more expressive, but "more expressive" means that you couldn't 1:1 replace it with another language's statements, which you do in your second example. So, the first example is not more expressive, but it is certainly more fluent.

Title: Modern frameworks method conventions


问:
Web Services vs Server Side Methods
With all the front end development frameworks now available.  I'd like to know if the generally accepted protocol is for a back end service to simply provide web services for the front end to consume?

For example: An application that may have displayed products in the past may have just generated the HTML on the server and sent it down to the client browser during the request.  It seems like the preferred way now would be to send the page template to the client, then the front end would make the request to get the list of products and display them using (Angular, Ember, React...)

Are there any performance cost to writing all client/server communication as web services?

答:
There is no generally accepted practice.  There are different architectural patterns for web applications.

The server-side presentation pattern has the entire work of generating a page done on ther server side.  The navigation in the application is between pages rendered entirely by the server.  This is the oldest model as it has been supported as long as HTML itself.

The single page application has a server-provided application loader page that may be static.  This page references a fully client-side application that will render pages and obtain content via XHR (large infrequent requests), EventSource (text-based server side events), Websocket (streamed, binary content), or WebRTC (realtime peer to peer audio/video) depending on need.  This is a popular model for recent web applications.

There are also hybrids of both approaches that enable optimizations of page load time and resource consumption.  An often overlooked aspect of web application development is power consumption on mobile devices.  A particularly bad example of this is a periodic XHR to obtain updates.  It will trigger the cellular radio to come on right after it has idled maximizing battery consumption and maximizing latency.

There are no straight forward absolute answers here.  There are some principles with obvious wins though:

Make as few requests as possible

Send as little data as possible (use efficient representations and compression)

Take advantage of caching (set Cache-Control and Last-Modified, and Etag headers correctly)

My personal experience with switching from server-side presentation to a single page application was a substantial improvement in responsiveness.  There are definitely downsides to having every data set on the page pulled down in a separate request.  The downsides are directly related to how they violate the principles above.     We had to learn to bundle data sets into fewer requests.

Interestingly with HTTP/2 the bundling is counter-productive because HTTP/2 supports multiple streams (standard requests or otherwise) on a single TCP connection.  Don't spend a lot of energy optimizing for HTTP/1.1 in ways that will hurt your app for HTTP/2.  This trade off is not completely straight-forward either as Khan Academy discovered.

In your case I would advise going with a client-side presentation framework.  It gives you more flexibility in rendering timelines and request counts.  More importantly it gives you an application that doesn't go to a white screen when the server processing a request chokes or disappears.  You can actually handle that as an exception on the client-side and provide user feedback and retry mechanisms.  I do not recommend server-side presentation frameworks except to facilitate more efficient delivery of single page applications.

Much more on this is available in Ilya Grigorik's High Performance Web Browser Networking.

Title: Web Services vs Server Side Methods


答:
Following the principle of least surprise, I think you should make your vector behave the same as the underlying numbers. Java is explicit about how floating-point is supposed to work (unlike C, for example), referencing IEEE 754.

So, yes, do allow non-finite values (infinity and NaN) and ±0. The one who uses your class will generally know best at what point to handle special values – if they need special handling at all – and you (in your vector class) cannot do much about them anyway. This will also greatly improve your performance because otherwise, you'd need countless conditionals all over the place and you'd probably still miss some cases anyway.

The same reasoning applies to implementing equality. If u and v are vectors of your class, then u.equals(v) should be true if and only if u.at(i) == v.at(i) is true for every valid index i.

Title: Should a generic vector class allow non-finite doubles as values?

Body:
I am currently writing an immutable multipurpose vector class in Java that essentially wraps a double[]. The class will be part of a game library, used to calculate entity positions, physics, pixel coordinates etc. I aim to make them also usable for other (non-game related) calculations.

The vector class provides basic operations such as (a and b are vectors):

a.length() (returning the length of the vector in Euclidean space)

a.add(b), a.scale(b) (adding or multiplying all vector components)

a.dot(b), a.cross(b) (calculating dot and cross product of a and b).

I am debating whether I should allow NaN, positive and negative infinity as vector values and whether I should distinguish between +0 and -0. Are there any reasons to why allowing non-finite doubles should be allowed? Is it even practical to implement operations for these methods - how should e.g. length() and scale(..) behave?

Another important concern I have are the methods a.hashCode() and a.equals(b). Should this be true:

```<code>new Vector(+0D, +0D, +0D).equals(new Vector(-0D, -0D, -0D));
</code>```

Considering that

```<code>Arrays.equals(new double[] { +0D, +0D, +0D }, new double[] { -0D, -0D, -0D }) == false
</code>```


问:
Bundling OpenJDK with a proprietary application allowed by GPL?
I am currently making a video game in Java that will most likely be distributed through Steam. Of course, many Steam users won't have Java already installed in this case. If this happens, I can either have a small native launcher that shows an informative dialogue telling the user they need to install Java, or simply bundle my own Java runtime environment (specifically OpenJDK 8) with my game. My game will be closed source, however it is based on an open source (BSD licensed) game engine.

I did look though OpenJDK's license. It is a GPL project which means that anything linking to it needs to be GPL as well. However, they also have the classpath exception. I'm not sure if the linking portion applies because my code isn't linking to it any more than it would be with or without bundling it. As far as I know, the classpath exception doesn't cover this use case.

There is a similar question on Stack Overflow, however that refers to the situation where an application is developed with OpenJDK, I am referring to distributing with OpenJDK.

答:
From what I read in the license you are freely able to redistribute the program, even charge to distribute it. </p>

<p>But as I have personal experience with releasing a Java game (not paid though) I find its better to just tell the user that Java Runtime Environment is required either on the distribution source (give them a link to the Java download) or have the application give the user an error. </p>

Body:
From what I read in the license you are freely able to redistribute the program, even charge to distribute it.

But as I have personal experience with releasing a Java game (not paid though) I find its better to just tell the user that Java Runtime Environment is required either on the distribution source (give them a link to the Java download) or have the application give the user an error.


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答:
"Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?"

Many, many people strive for "ultimate" quality at the expense of something that is (a) simple, (b) reliable and (c) correct.

The most important way to speed up your development is to simplify what you are doing so that it is absolutely as simple as possible.

Most folks that have problems with delivering on time are delivering way, way too much.  And the reasons given are often silly.  They're often just perceived requirements, not actual requirements.

I've heard a lot of people tell me what the customer "expects".  This is a bad policy.

Build the simplest possible thing.  If the customer requires more, build more.  But build the simplest possible thing first.

Title: How to become a "faster" programmer?


问:
Is there anything that can be done with recursion that can't be done with loops?
There are times where using recursion is better than using a loop, and times where using a loop is better than using recursion. Choosing the "right" one can save resources and/or result in fewer lines of code.

Are there any cases where a task can only be done using recursion, rather than a loop?

答:
If the recursive call is the very first or very last statement(excluding condition checking) of a recursive function, it is pretty easy to translate into a looping structure.

But if the function does some other things before and after the recursive call, then it would be cumbersome to convert it to loops.

If the function have multiple recursive calls, the converting it to code which is using just loops will be pretty much impossible. Some stack will be needed to keep up with the data. In recursion the call-stack itself will work as the data-stack.


问:
Are include guards necessary if headers only contain declarations?
Consider the following assumptions about C programming (some of which go too far, I confess):

Putting any variable definitions in a header file is incorrect, because each translation unit creates its own copy of the data. And if it's extern and used from more than one place, we get UB. The correct usage is to declare variables in header files and define them in the corresponding implementation files.

Macros are bad form and can usually be converted to variables or functions.

Redeclaration of functions is completely legal.

PROVIDED the above is followed, include guards become unnecessary. There is an exception for inline functions, which have to be defined in the header, but many projects do not use them.

Given all of that, why is the include guard an industry standard? Most IDEs even add them automatically upon file creation.

答:
In many (most?) non-trivial projects, header files contain typedef declarations or struct definitions. Neither of these are allowed to be repeated in a single translation unit (pre-processed source file).

As there are non-repeatable elements that are commonly placed in header files, and those elements also belong in a header file, it has become automatic for C (and C++) programmers to put include guards in their headers.

In C++, it is even more common, as inline functions are used much more and class definitions have the same restriction as struct definitions that they can't be repeated.


问:
Is it good practice to catch a checked exception and throw a RuntimeException?
I read some code of a colleague and found that he often catches various exceptions and then always throws a 'RuntimeException' instead. I always thought this is very bad practice. Am I wrong?</p>

答:
There are really a couple of questions here

Should you transform checked exceptions into unchecked ones?

The general rule of thumb is that exceptions that the caller is expected to catch and recover from should be checked. Other exceptions (ones where the only reasonable outcome is to abort the whole operation or where you consider them unlikely enough that worrying about handling them specifically is not worth it) should be unchecked.

Sometimes your judgement on whether an exception deserves catching and recovery is different from that of the API you are working with. Sometimes context matters, an exception that is worth handling in one situation may not be worth handling in another. Sometimes your hand is forced by existing interfaces. So yes there are legitimate reasons to turn a checked exception into an unchecked exception (or to a different type of checked exception)

If you are going to turn an unchecked exception into a checked exception how should you do it.

Firstly and most importantly make sure you use the exception chaining facility. That way the information from the original exception is not lost and can be used for debugging.

Secondly you have to decide what exception type to use. Using a plain runtimeexception makes it harder for the caller to determine what went wrong but if the caller is trying to determine what went wrong that may be an indication that you should not have changed the exception to make it unchecked.


问:
How to document **kwargs in python?
I have a function which has a large number of arguments.

I want to have the names of the arguments available in the help() function, but I want the results as a dict.

At the moment, I have the following:

```<code>def myfunc(thisparameter,thatparameter,hostname,password,port,service,url,someotherparameter, etc, andsoforth):
   return some_function(dict(thisparameter=thisparameter,thatparameter=thatparameter,hostname=hostname,port=port,service=service,url=url,someotherparameter=someotherparameter, etc=etc, andsoforth=andsoforth))
</code>```

I can't just use kwargs, since that means the help() function won't show the parameters. I have a lot of these. I understand that I can use __doc__, but that still shows the parameters as **kwargs.

答:
You could use the locals() hack proposed in this SO question, like so:

```<code>def myfunc(thisparameter,thatparameter):
  return some_function(**locals())
</code>```

This allows you to explicit arguments to myfunc and call your implementation without the need to repeat all the arguments.

It is not bulletproof. For a more "secure" version you might want to use inspect.

(As a side note, I'm flagging this question for migration to SO. I'm however not so sure if this is a duplicate as you have the help twist that is not mentioned in the SO question)

Title: How to document **kwargs in python?

Body:
You could use the locals() hack proposed in this SO question, like so:

def myfunc(thisparameter,thatparameter):
  return some_function(**locals())

This allows you to explicit arguments to myfunc and call your implementation without the need to repeat all the arguments.

It is not bulletproof. For a more "secure" version you might want to use inspect.

(As a side note, I'm flagging this question for migration to SO. I'm however not so sure if this is a duplicate as you have the help twist that is not mentioned in the SO question)


答:
Deleting or excluding a line of code definitely is an indication of the end of its lifespan.

Regrading editing, I would ask this question: Does this statement produces a different outcome after the edit?

If the answer is yes, then I'd say the previous statement is no longer available, otherwise I'd still consider it as the continuation of the previous statement.

Example of changing the outcome:

```<code>if ( a && b )
</code>```

to:

```<code>if ( a || b )
</code>```

Example of continuing the lifespan:

```<code>foo.bar( baz );
</code>```

to:

```<code>foo.prototype.bar.call( this, baz );
</code>```

Title: How can I estimate the lifespan of a line of code?

Body:
I'm trying to figure out a way to analyze code longevity in open source projects: that is, how long a specific line of code is active and in use.

My current thinking is that a line of code's lifespan begins when it is first committed, and ends when one of the following occurs:

It's edited or deleted,

Excluded from builds,

No code within its build is maintained for some period of time (say, a year).

NOTE: As clarification on why an "edit" is being counted as "death", edited lines would be counted as a "new" generation, or line of code. Also, unless there's an easy way to do this, there would be no accounting for the longevity of a lineage, or descent from an ancestor.

What else would determine a line of code's lifespan?

Body:
Deleting or excluding a line of code definitely is an indication of the end of its lifespan.

Regrading editing, I would ask this question: Does this statement produces a different outcome after the edit?

If the answer is yes, then I'd say the previous statement is no longer available, otherwise I'd still consider it as the continuation of the previous statement.

Example of changing the outcome:

if ( a && b )

to:

if ( a || b )

Example of continuing the lifespan:

foo.bar( baz );

to:

foo.prototype.bar.call( this, baz );


问:
Patterns for passing context through a method chain
This is a design decision that appears to come up quite a lot: how to pass context through a method that doesn't need it to a method that does. Is there a right answer or does it depend on the context.

Sample code that requires a solution

```<code>// needs the dependency
function baz(session) {
  session('baz');
}

// doesn't care about the dependency
function bar() {
  baz();
}

// needs the dependency
function foo(session) {
   session('foo')
   bar();
}

// creates the dependency
function start() {
  let session = new Session();
  foo(session);
}
</code>```

Possible solutions

threadlocal

global

context object

pass the dependency through

curry baz and pass it into bar with the dependency set as the first arg

dependency injection

Examples of where is comes up

HTTP request processing

Context objects in the form of request attributes are often used: see expressjs, Java Servlets or .net's owin.

Logging

For Java logging folk often use globals / singletons. See the typical log4j / commons logging / java logging patterns.

Transactions

Thread locals are often used to keep a transaction or session associated with a chain of method calls to avoid needing to pass them as parameters to all the methods that don't need them.

答:
If bar is dependent on baz, which in turn requires dependency, then bar requires dependency too in order to correctly use baz. Therefore, the correct approaches would be to either pass the dependency through as a parameter to bar, or curry baz and pass that to bar.

The first approach is simpler to implement and read, but creates a coupling between bar and baz. The second approach removes that coupling, but could result in less clear code. Which approach is best will therefore likely depend on the complexity and behaviour of both functions. For example, if baz or dependency have side effects, ease-of-testing will likely be a large driver in which solution is chosen.

I'd suggest all the other options you propose are both "hacky" in nature and likely to lead to problems both with testing and with difficult to track down bugs.


问:
Factory of factories?
I have concrete factory classes which implement MyFactory interface. I  want to get concrete factory objects based on parameter. How to do this?

One way is to create factory of factories[FoF],  and FoF would be parameterized factory.

Is there any more elegant way to do this?

This is purely intellectual exercise, I am not facing any problem in my project.

答:
A single BikeFactory should be able to produce different Bikes - so a user chooses a red Harley with a teddy bear on the handlebar. You simple need two arguments to your BikeFactory::createBike - the bike type, and the options (red paint, and handlebar decoration).

Your BikeFactory then creates a Harley, and injects the options into that instance of Harley.

You don't need a specific Harley factory - Harleys are built the same as Suzukis/Hondas/Sanchezes.

Title: Factory of factories?


答: Notice when you have been reading Stack Overflow for too long.  The "Compiling" excuse only works for so long. :)</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: Matthew Jones


答:
Yes, you would have Factory of Factories. The key point is that this either class or method should be in topmost library/application. Only smallest possible part of the application should know about this FoF. It could very well be a simple method in launcher of the application that is executed before the main loop of the application executes.

If you were tempted to create interface for this FoF, then that would be indication that your creation scheme might use redesign.

Edit : It seems we need to clarify what I mean by Factory (actually Abstract factory, but I don't consider "a Factory" as pattern. Abstract Factory pattern is solution to a situation, where some piece of code needs to create an instance, but the piece of code itself doesn't have enough information to decide which instance to create. That is why the client exposes an abstraction and someone who has information to create that instance realizes that abstraction.

If you want to talk about design, you MUST ALWAYS tell us how is it going to be used and who has what information.

Title: Factory of factories?

Body:
I have concrete factory classes which implement MyFactory interface. I  want to get concrete factory objects based on parameter. How to do this?

One way is to create factory of factories[FoF],  and FoF would be parameterized factory.

Is there any more elegant way to do this?

This is purely intellectual exercise, I am not facing any problem in my project.


问:
Should I use TDD and BDD if my project is changing fast?
I have my own little project I am creating using RoR, I plan it to have small-medium load.

With no doubt I started with BDD and TDD (Cucumber and RSpec to be exact, but I am also experienced with TestUnit), I like it but since it's my own project and it's a somewhat startup - I am changing many things in it, many requirements, many ideas how things should work and look. So it becomes too much time-consuming to always code it using BDD and TDD, even if I cover only common cases.

What should I do? Should I sacrifice BDD and TDD for productivity till I get to some point when I have a solid basis and it's time for production, and than I write tests?

Should I write them right now but as minimal as possible? Should I only write RSpec and forget about Cucumber for now? Or maybe just TestUnit to test model for now since it's the most important and everything else can change?

Thanks in advance!

Update:

I know all the pros of TDD and BDD, by no means it makes it easier to scale and bugfix application in future and save time, but maybe it's more reasonable in my situation to wait few weeks till I have at least some skeleton architecture of my app and than once I am sure with it I can cover it with tests to have a solid base? And than continue with TDD and do all the tests with TDD.

答:
It's fine - with provisos.  I think your question can be rephrased simply as - "is it OK to take on technical debt?"

i.e.
Is it OK to produce things in a quick and dirty way when other factors demand it?

To which the slightly woolly answer is "yes, sometimes - as long as you pay off your debts".

There's further nuances to your question.  Such as whether TDD will actually slow you down that much.  I would argue that, assuming you already know how to do TDD and how to use those tools, then it won't slow you down at all.  It will force you to make design decisions that you would have encountered anyway, and probably help you solve them more quickly.  If, on the other hand, it's going to take you some time to learn the methodology and the tooling, then it might not be plausible to factor in all that learning time too.

The second is whether those other factors really demand you to take on technical debt.  Startups and new products are a pretty natural habitat for technical debt.  If not getting something out by a given time means going out of business, then you better take on some technical debt.  If taking on some technical debt means the prototype of your self-driving car might crash, it's better to delay the release.  I don't think technical debt should de facto be the first thing to cater for a tight deadline - pushing back to stakeholders for a delayed release (or same date different scope) should be your first option, whenever possible.

Lastly, are you sure you're going to pay off your debt in a timely fashion?  Are you really, really sure?  It is all too easy to give in to external factors (they never seem to go away) and eventually you get to a point where all you're doing is paying off the interest on your debt.


问:
Is it better to check `c >= '0'` or `c >= 48`?
After a discussion with some my colleagues, I've a 'philosophical' question about how treat the char data type in Java, following the best practices.

Suppose a simple scenario (obviously this is only a very simple example in order to give a practice meaning to my question) where, given a String 's' as input, you have to count the number of numeric characters present in it.

These are the 2 possible solutions:

1)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= 48 && s.charAt(i) <= 57) {
            n++;
        }
    }
</code>```

2)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
            n++;
        }
    }
</code>```

Which of the two is more 'clean' and compliant with the Java best practices?

答:
Regular Expressions (RegExs) have a specific character class for digits - \d - that can be used to remove any other character from your string. The length of the resulting string is the desired value.

```<code>public static int countDigits(String str) {
    str = Objects.requireNonNull(str).trim();

    return str.replaceAll("[^\\d]", "").length();
}
</code>```

Notice, however, that RegExs are computationally more demanding than the other proposed solutions therefore they should not be generally preferred.

Body:
Regular Expressions (RegExs) have a specific character class for digits - \d - that can be used to remove any other character from your string. The length of the resulting string is the desired value.

public static int countDigits(String str) {
    str = Objects.requireNonNull(str).trim();

    return str.replaceAll("[^\\d]", "").length();
}

Notice, however, that RegExs are computationally more demanding than the other proposed solutions therefore they should not be generally preferred.


答: Indeed, when using the Abstract Factory pattern, somewhere in your program a decision must be made which of the concrete Factory classes will be instantiated. And the method which does this will typically be a Factory method. It will be less confusing if you distinguish clearly between these two terms.</p>

Title: Factory of factories?


答:
The only fair answer is that it depends on your programming paradigm's idioms. If you're using OO, it's almost certainly incorrect to pass a dependency from method to method to method. It's a code smell in OO. In fact, that's one of the problems OO solves -- an object fixes a context. So in OO, one correct (there are always other ways) approach is to deliver the dependency via contructor or property. A commenter mentions "Dependency Injection" and that's perfectly legit, but it's not strictly necessary. Just provide the dependency so it's available as a member to foo and baz.

You mention currying, so I'll assume functional programming isn't out of the question. In that case, a philosophical equivalent of object context is closure. Any approach that, once again, fixes the dependency so it's available to dependents works just fine. Currying is one such approach (and it makes you sound smart). Just remember there are other ways to close over a dependency. Some of them are elegant and some of them awful.

Don't forget about Aspect-oriented programming. It seems to have fallen out of favor in the last few years, but its primary goal is solving exactly the problem you describe. In fact, the classic Aspect example is logging. In AOP, the dependency is added automatically after other code is written. AOP folks call this "weaving". Common aspects are woven into the code at the appropriate places. This makes your code easier to think about and is pretty darn cool, but it also adds a new testing burden. You'll need a way to determine your final artifacts are sound. AOP has answers for that as well, so don't feel intimidated.

Title: Patterns for passing context through a method chain

Body:
This is a design decision that appears to come up quite a lot: how to pass context through a method that doesn't need it to a method that does. Is there a right answer or does it depend on the context.

Sample code that requires a solution

```<code>// needs the dependency
function baz(session) {
  session('baz');
}

// doesn't care about the dependency
function bar() {
  baz();
}

// needs the dependency
function foo(session) {
   session('foo')
   bar();
}

// creates the dependency
function start() {
  let session = new Session();
  foo(session);
}
</code>```

Possible solutions

threadlocal

global

context object

pass the dependency through

curry baz and pass it into bar with the dependency set as the first arg

dependency injection

Examples of where is comes up

HTTP request processing

Context objects in the form of request attributes are often used: see expressjs, Java Servlets or .net's owin.

Logging

For Java logging folk often use globals / singletons. See the typical log4j / commons logging / java logging patterns.

Transactions

Thread locals are often used to keep a transaction or session associated with a chain of method calls to avoid needing to pass them as parameters to all the methods that don't need them.


问:
Avoid copy and paste programming, what pattern to use?
I have a small software that generates some Word documents. It reads a template, runs a few SqL procedures to get the data, generates the documents and then sends them via e-mail. It's quite simple.

Right now I want to apply that logic to generate another type of report, the base word template will change and it will run different queries. I can do this (wrongly) by copy pasting the code, but I want to extend the current app to generate both reports.

What I can't figure out is what software pattern I need to apply to solve this situation.

答:
The usual way is to refactor the common functionality into its own method or class, and then call that method or class from those two places, passing the required information to the class through its method or constructor parameters.

See Also

Refactoring on Wikipedia