Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

in JavaScript:

function getTopCustomersOfTheYear(howManyCustomers, whichYear) {
   // Some code here.
}
getTopCustomersOfTheYear(50, 2010);

in C#:

public List<Customer> GetTopCustomersOfTheYear(int howManyCustomers, 
 int whichYear)
{
   // Some code here
}
List<Customer> customers = GetTopCustomersOfTheYear(50, 2010);

in PHP:

public function getTopCustomersOfTheYear($howManyCustomers, $whichYear)
{
   // Some code here
}
$customers = getTopCustomersOfTheYear(50, 2010);

Is there any language out there which support this syntax:

function GetTop(x)CustomersOfTheYear(y)
{
    // Some code here
}
returnValue = GetTop(50)CustomersOfTheYear(2010);

Isn't it more semantic, more readable form of writing a function?

Update: The reason I'm asking this question is that, I'm writing an article about a new syntax for a new language. However, I thought that having such syntax for declaring methods could be nicer and more friendly to developers and would decrease learning-curve of the language, because of being more closer to natural language. I just wanted to know if this feature has already been contemplated upon or not.

share|improve this question
10  
It might be easier to read, once you get used to the idiom, but it seems to me it would be difficult to write a correct parser for that. – Mason Wheeler Aug 22 '11 at 17:35
2  
What do you mean by "placeholders?" This question is hard to understand as posed, though the last code example is reminiscent of Objective-C and SmallTalk. – greyfade Aug 22 '11 at 17:44
1  
Hi @Mark. Well, my problem is that, I'm trying to write an article about a new syntax for a new language. However, in this new syntax, I thought that having such ability could be regarded as more close to human language. But I didn't know any example of any language which is using this syntax, because I only know PHP, C#, and JavaScript. Thus I asked it here. I'll really appreciate it if you reopen the question. Thanks :) – Saeed Neamati Aug 22 '11 at 18:17
3  
AFAIK Smalltalk was the first language using this syntax exclusively like 'hello world' indexOf: $o startingAt: 6 or Rectangle width: 100 height: 200. Btw., what's wrong with this question? – maaartinus Aug 22 '11 at 18:20
2  
If you move a parenthesis, you get: returnValue = GetTop(50, CustomersOfTheYear(2010)) which looks to me equally readable, and actually more flexible/orthogonal. ...and yeah, it's plain normal syntax. – arnaud Aug 23 '11 at 21:16
show 4 more comments

11 Answers

up vote 33 down vote accepted

Yes, and yes. Yes there's such a language, and yes, many people find it more readable once they get used to it.

In Objective-C, the method would be:

- (NSArray*)getTop:(int)count customersOfTheYear:(Year)year;

That's actually a pretty contrived example that doesn't read very well, so here's a better one from actual code:

+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha;

That the prototype for a method that returns a new UIColor instance using the red, green, blue, and alpha values. You'd call it like this:

UIColor *violet = [UIColor colorWithRed:0.8 green:0.0 blue:0.7 alpha:1.0];

Read more about message names with interspersed parameters in The Objective-C Programming Language.

share|improve this answer
6  
+1 I wish every language did this. <3 Objective C. – Mitch Lindgren Aug 23 '11 at 16:00
6  
First time I read about it in Objective C I thought it was clever, but it's actually named parameters made more stiff and harder to manage. Apart from that, good answer. – ZJR Aug 24 '11 at 15:28
2  
An example of how the method is invoked would not go amiss. – greyfade Aug 24 '11 at 16:58
2  
@ZJR, despite Wikipedia's opinion to the contrary, Obj-C's style is like named parameters, but different. In the example above, the method name is: +colorWithRed:blue:green:alpha:. I happened to use names for the parameters that match the method, but I could as easily have used r, b, g, and a. With named parameters such as JavaScript offers, you'd use the actual names given to access the values. True names parameters can also usually be given in any order, and parameters may be optional. So similar, yes, but fundamentally different. – Caleb Aug 24 '11 at 21:42
2  
@ZJR, your python example is right on -- that's exactly what I'd call "named parameters." I'm just saying that Obj-C really doesn't give you that at all. The syntax looks a lot like JavaScript's named parameters because the method is broken up into parts, and each part has a colon, but it's really not that at all. The names in Obj-C are part of the method name, not names that can be used to refer to the parameters in the implementation; order matters; parameters aren't optional. I suspect we probably agree more than not. – Caleb Aug 25 '11 at 4:33
show 3 more comments

Objective-C does that. Here is a typical prototype:

- (void) areaWithHeight: (float) height andWidth: (float) width;

Here is how you call such a method:

float area = [self areaWithHeight: 75 andWidth: 20];

Objective-C is primarily used with Cocoa for Mac OS X and Cocoa Touch for iOS, but gcc will build Objective-C code on just about every platform that gcc works on.

share|improve this answer
Sorry that bullet should have been a hyphen. I guess hyphens in answer text are taken as markup. Hyphens in Objective-C are used to declare methods that belong to an object - [foo bar: x] where foo is an object or class instance - while plus signs are used for class methods, what C++ refers to as static member functions. – Michael Crawford Aug 22 '11 at 17:47

Answer: smalltalk

http://en.wikipedia.org/wiki/Smalltalk

'hello world' indexOf: $o startingAt: 6 is like Java's "hello world".indexOfStartingAt(o, 6)

Rectangle width: 100 height: 200 is like Java's new Rectangle(100, 200)

The syntax is... expression word1: parm1 word2: parm2 word3: parm3 ... The name of the method called is the concatenation of all the words.

share|improve this answer

I believe you are looking for the abstraction called "fluent interface (I am hereby raising a comment, originally made by @Jesper, to an "answer")." This now common pattern has been successfully implemented in many languages, of which Objective-C is only one.

Here is a pretty clean example:

Person bo = new Person();
bo.Set.FirstName("Bo").LastName("Peep").Age(16).Size("Little").LostHerSheep();

You can see how something like this can be implemented in Randy Patterson's How to design a fluent interface.

Andre Vianna gives a brief history and then discusses possible implementations in two more article parts, including plenty of useful information. Vianna points back to the old idea I first encountered in Smalltalk 80 called "cascading," that enabled sending multiple messages to the same object. It looked like this:

aThing one: 'one';
  two: 'two';
  other.

Cascading subsequently evolved into "method chaining," where we "Make modifier methods return the host object, so that multiple modifiers can be invoked in a single expression." Method chaining later grew up to become the fluent interface concept we know and use frequently today. What you plan to do looks very similar.

Ayende Rahien discusses how "fluent interface" may differ significantly enough from "method chaining" to deserve its own name.

Fluent interfaces are commonly seen in some of the new tools used in behavior driven development (BDD) and have even found their way into NUnit, a major .NET unit testing tool, in its new Constraint-Based Assert Model.

These basic approaches have subsequently been implemented in other languages, including Ruby, Python, C#, Objective-C and Java. To implement something similar, you will want to study up on the idea of "closure," which is pretty much fundamental to chaining and fluency.

Perhaps you can improve on these models; that's how we get great new languages. Still, I believe that fully understanding method chaining and fluent interfaces will give you a great starting point from which to evolve your ideas!

share|improve this answer
1  
+1 for most researched answer so far, though adding examples and re-wording for readability might help. – haylem Aug 24 '11 at 2:34
@haylem, thank you for making me go back and add examples and a bit more detail! – John Tobler Aug 24 '11 at 16:30
2  
Upvoted because it's a good description of the fluent style, but please note that this really isn't what the OP is asking about. As I read it, the question relates to interspersing parameters with parts of the name of a single function or method. Note the proposed function declaration: function GetTop(x)CustomersOfTheYear(y). This is a single function, not chained calls to two different functions. – Caleb Sep 20 '11 at 20:02

In Common lisp, you can define keyword arguments for a function like this:

(defun area (&key width height)
    (* width height))

The function is called like this:

(area :width 2 :height 3)

In Ada you don't need a special declaration - you can call any procedure or function alternatively by listing the arguments in order, or by naming the arguments like this:

a := area(width => 2, height => 3);

Finally, the boost library includes a layer of hacks to add the feature to C++: http://www.boost.org/doc/libs/release/libs/parameter/doc/html/index.html

share|improve this answer

Python has keyword parameters. Function definition example

def getTopCustomers(count,year):
...

Function call example

x = getTopCustomers(year=1990, count=50)

(I understand this is not be quite in the spirit of the original question, but if keyword parameters in lisp qualifies, so do this. In Smalltalk and Objective-C, however, the keywords between arguments are really part of the function name/lookup.)

share|improve this answer

I couldn't find the name of it, but there's a design pattern to accomplish something similar, where a function call returns a new object modified as described. For example:

query = db.getTopCustomers(50).forYear(2010);

It isn't used very often because your data has to be very orthogonal in order to avoid unmanageable complexity under the hood, but can be useful in the right circumstances.

share|improve this answer
6  
This is called the fluent interface design style. – Jesper Aug 22 '11 at 21:52
@Jesper, what I see is very similar to jQuery chaining. Am I right? – Saeed Neamati Aug 23 '11 at 4:45
Yes, @Saeed, jQuery uses this style. – Karl Bielefeldt Aug 23 '11 at 13:38

In JavaScript or any other language that supports closures, you can curry a function like this:

function getTopCustomersFunc(count) {
    return function(year) {
       // run some query, return count customers from year
    }
}
var top20Func = getTopCustomersFunc(20);
var top20Customers2005 = top20Func(2005);
var top20Customers2008 = top20Func(2008);
share|improve this answer
1  
+1 because this is interesting, but remember that the '20' in top20Func is no longer a parameter but part of the name that reminds you of the parameter. You could just as easily say: var top5Func = getTopCustomersFunc(37);. The '5' is misleading here, but the code works exactly the same as if the variable had been named top37Func. – Caleb Sep 20 '11 at 20:08

While not a programming language per se, Cucumber takes parameters in the middle of function names, which can include spaces and are meant to look like English.

The 'functions' are defined in Ruby however

# definition
Given /^I calculate (.*) times (.*)$/ do |x, y|
    @result = x.to_i * y.to_i
end

Then /^the result should be (.*)$/ do |v|
    @result.should == v.to_i
end

# usage
Scenario:
    Given I calculate 6 times 9
    Then the result should be 42
share|improve this answer

This depends on your definition of "language", but the robotframework testing framework lets you define keywords this way. From their documentation on embedded arguments:

Select ${animal} from list | Open page | pet selection
                            | Select item from list | animal_list | ${amimal}

The above declares a new keyword (essentially a function) named "select ${animal} from list" where '${animal}' is a parameter. You call it like "select cat from list"

share|improve this answer
This seems to me like SQL statements. +1 – Saeed Neamati Aug 25 '11 at 4:52

Inform 7.

To create (employee - a person) being paid (salary - a number):
    say "Welcome to your new job, [name of employee]!";
    choose a blank row from the table of employees;
    now the paid entry is the salary;
    now the name entry is the name of the employee.

And so on.

share|improve this answer
3  
This doesn't exactly explain how syntax of the language works. Many people are not familiar with the Inform language and cannot distinguish the parameters from the call or its use in other areas of the code. – MichaelT Feb 16 at 22:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.