Skip to main content

proposal for more readable methods names

1 reply [Last post]
enricjaen
Offline
Joined: 2007-08-22
Points: 0

Hopelly this is the correct forum.

It's considered a good practice that method names be descriptive (no need of apidoc) and somehow describe its parameters. However parameters are always grouped at the end.

I'd like to propose a new syntax for methods that I think makes code more readable. Here are 4 examples:

example 1)

traditional way:

add(2,3);

add(int a, int b) {
//code here...
}

proposed:

add(2)plus(3);

add(int a)plus(int b)  {
//code here...
}

example 2)

traditional:

sayGreetingToPerson(greeting,person)

sayGreetingToPerson(String greeting, String person) {
// code here ..
}

proposed:

say("Hello")to("John");

say(String greeting)to(String person) {
// code here
}

example 3)

traditional way:

getItemFromFile(file,item);

getItemFromFile(File file,String item)  {
//code here...
}

proposed:

getItem(item)fromFile(file);

getItem(String item)fromFile(File file)  {
//code here...
}

or maybe so:

get(item)from(file);

get(String item)from(File file)  {
//code here...
}

example 4)

traditional way:

perform(tiles, request, response, context);

perform(ComponentContext tilesContext,
                       HttpServletRequest request,
                       HttpServletResponse response,
                       ServletContext servletContext) {
//code here..
}

proposed:

performWith(tiles)the(request)returning(response)inContext(context);

performWith(ComponentContext tilesContext)
        the(HttpServletRequest request)
        returning(HttpServletResponse response)
        inContext(ServletContext servletContext) {
//code here...
}

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
surfman
Offline
Joined: 2006-11-23
Points: 0

Whether is more readable is open for debate. What you are describing is method chaining/Builder pattern:

(From Wikipedia)

class Person {
        private String name;
        private int age;

        // In addition to having the side-effect of setting the attributes in question,
        // the setters return "this" (the current Person object) to allow for further chained method calls.

        public Person setName(String name) {
                this.name = name;
                return this;
        }

        public Person setAge(int age) {
                this.age = age;
                return this;
        }

        public void introduce() {
                System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
        }

        // Usage:
        public static void main(String[] args) {
                Person person = new Person();
                // Output: Hello, my name is Peter and I am 21 years old.
                person.setName("Peter").setAge(21).introduce();
        }
}