SlideShare a Scribd company logo
APP DEV WORKSHOP
I
T IS OFTEN SAID THAT GOOD DESIGN IS INVISIBLE.
What does this mean for something like an
interface, which is intentionally a highly visible
boundary separating different parts of a system?
Interfaces are about communication, both between
different components of the system and between
the code and the user. A well-designed interface is
typically concise, consistent and conventional.
Which all sounds a bit dull at first sight, but that
is, after all, what it means to be invisible: there is
little that is out of the ordinary and little to write
home about.
Given the significant role that interfaces play in
a system – whether we are talking about the
interface presented by a header file, a class’s public
section, the interface construct found in Java, C#,
IDL and other languages, a package’s public section
or even a whole API – the “principle of least
astonishment” is perhaps one of the most important
guidelines to follow:
q Concise: Interfaces that try to be helpful by
accommodating all possible needs in all possible
ways are particularly unhelpful and
unaccommodating. An interface should be
minimal, but not to the point of being cryptic.
The less there is to read, learn and remember,
the easier an interface will be to use.
q Consistent: An interface that is consistent in its
partitioning and naming is easier to anticipate
and offers fewer surprises than one that seems
to be designed in a fragmented and disconnected
fashion, following one style in one part of the
interface and another style in a different part of
the interface.
q Conventional: In selecting names, partitioning
method and class responsibility, and organising
argument lists and return values, follow established
practice where such practice is itself concise
and consistent – don’t invent new styles or
follow obscure ones unnecessarily, but don’t
slavishly follow common but poor forms. An
interface that follows the idioms of the language
and environment will be more readily grasped
than one that does not.
Nevertheless, being concise, consistent and
conventional is not quite as dull as it first appears:
it simply shifts the emphasis and effort of interface
design to more weighty matters, and away from
the trivial. The use of idioms (expressions and
phrasing specific to a cultural grouping) is in
contrast to the use of idiolects (affectations of
expression peculiar to an individual), wresting
responsibility for certain possible, arbitrary
variations away from interface designers, and
freeing them up to focus on other design issues.
The responsibility placed on the designer becomes
more one of judgement and breadth of knowledge
than one of invention.
Signature contracts
Interfaces play the role of contracts between
different parts of a system1
, and there are many sides
to drawing up such a contract2
.The appearance and
basic use of an interface constitutes a signature
contract: names, types and argument lists. Developers
familiar with the contract metaphor often overlook
contracts that are not functional contracts, and they
often assume that functional contracts are always
– and can always – be expressed using only pre- and
postconditions3
.
Most generally, a contract is an agreement that is
binding and typically enforceable, with consequences
for any transgression. The use of assertions to
enforcecorrectnessofusageandimplementationallows
some contractual aspects to be expressed, but it does
not cover everything. In statically typed languages,
signature contracts tend to be enforced at compile
time: incorrect usage leads to a compilation error.
In dynamically typed languages, or via reflection,
signature contracts are checked at runtime:
transgressions are signalled by exceptions.When going
through weakly typed interfaces, such as via void *
in C, any requirements on a type that are not met
will lead to undefined behaviour – a laissez faire
enforcement policy with crashing consequences.
Style and idiom
Consider a simple sorting facility, along the lines
discussed in a previous column2
. Narrowing the scope,
consider sorting an array or subarray of integers.What
would be the most idiomatic way of presenting this
facility in C?
void sort(int array[], size_t how_many);
APP DEV WORKSHOP
Defining an interface is more than just putting a front on an implementation.
Kevlin Henney looks into the intentional side of interface design
Form follows function
38 APPLICATION DEVELOPMENT ADVISOR q www.appdevadvisor.co.uk
MARCH–APRIL 2004 39
And in C++?
void sort(int *begin, int *end);
And in Java?
...
public static void sort(int[] array, int from, int to) ...
...
In each case the operation is named sort and returns void. However,
in spite of the syntactic similarities between the languages, all other
details are different. Although it is sometimes possible to adopt
one language’s idiom in another, this often leads to an inappropriate
look and feel in the borrowing language. The style may work in
a technical sense – it compiles and runs – but it may not make the
best use of language features or communicate most effectively –
it is more idiolectic than idiomatic.
For example, although it is possible to adopt the C-style
signature for sort in C++, the native C++ approach for expressing
algorithms is based on iterator ranges, as used through the
Standard Template Library (STL). If the type of the underlying
container is generalised to allow any random-access sequence, not
just an array, or the type of the elements to be sorted can be anything
that can be ordered using the < operator, the sort function
generalises directly to the common function template appearance
of the STL algorithmic operations:
template<typename iterator>
void sort(iterator begin, iterator end);
Each of the suggested signatures reflects a similar set of
capabilities: the ability to take an array of integers and sort all or
part of it. In C the subrange is communicated by passing a
pointer to the starting element and the count of how many
elements after that should be considered, expressed as the
standard size_t type, used for denoting sizes, rather than a
plain int. This signature takes advantage of C’s close (sometimes
too close) relationship between pointers and arrays. By contrast,
C++’s notion of subrange is based on an iterator that points to
the beginning and one to the first element past the end of the
subrange.
Java does not allow pointer–array aliasing, so although its
signature is similar to the C version, it must name the base of the
array explicitly. Java then specifies the subrange using integer indices.
Like the C++ version, its range is half-open, i.e. the first index is
included in the range but the last is not. An alternative would have
been to specify the start followed by the number of elements to
be sorted rather than the start and the end indices. However, this
is not the convention in common use elsewhere in the Java
libraries, so although it has its own merits, those are not enough
to outweigh the use of the more idiomatic form.
In C and C++ the operation name is global and, in C++,
perhaps nested within a namespace. In Java there is no mechanism
for defining global operations, so sort needs to be defined in the
context of a utility class, which raises new questions. What
should be the granularity and scope of such a utility class? A class,
Sort, that holds only the single static sort method; a class, Sorting,
that holds sort and any related methods, such as an isSorted predicate;
a class, named something like ArrayUtilities, that holds sort and
other unrelated methods that operate on arrays. The first option
is too fine grained and offers no useful room for expansion, with
the exception of adding other sort overloads. The third option is
the one used by the Java Collections API, and should be avoided
as being little more than a coincidental and un-cohesive aggregation
of functionality. The second option is probably the wisest in
this case.
Useful, usable and recently used
There were few naming issues in considering the sorting facility:
sort was sufficiently concise and conventional. The stylistic
concerns were focused mainly on the argument list. Let’s take another
example that demonstrates a broader interface to a commonly used
facility, but one that is less frequently commoditised than sorting:
a recently used list.
Application menus often hold a list of the most recently opened
documents and modern phones normally hold a list of the most
recently dialled numbers. A recently used list is often bounded to
an upper capacity.The general behaviour is that of a dispenser type,
such as a stack or a priority queue, with the property that the most
recently inserted element is found at the front and that an
element occurs only once in the whole sequence, i.e. no element
is equal to any other element.
To keep things simple, rather than focus on holding arbitrary
objects that may be mutable and could undermine the uniqueness
invariant on the list, just consider the interface to a recently
used list that holds strings. What would this look like in Java?
interface RecentlyUsedList
{
boolean isEmpty();
int size();
int capacity();
void clear();
void push(String newHead);
String elementAt(int index);
...
}
This interface follows standard Java capitalisation conventions
and uses names found in the Java library. In the Java Collections
API the name isEmpty is favoured over the less commonly used
empty convention, which would be the appropriate name for such
an operation in C++. Notice that the common but rather lame
get prefix convention is avoided in naming size and capacity.
This prefixing convention is over-applied by many programmers,
with the typical effect of making their code look like a form of
high-level assembler. Joshua Bloch intentionally avoided this style
in the design of much of the Java Collections API 4
, favouring the
clearer and more direct adjective style for queries about properties.
There is some inconsistency in Java over what to call the size
or length query: arrays use a length field; strings use a length method;
collections use a size method. As a RecentlyUsedList represents
a collection, it makes sense to adopt size.The most related notion
to an upper limit is the capacity method found in Vector,
which also has the virtue of being a concise name. There is
little contention or uncertainty in naming the clear method, which
is the conventional form used in Java and other languages.
If a recently used list is in some ways like a queue or a stack,
common received wisdom suggests that push is the most likely
candidate name for the insertion operation. Java’s Stack class
does indeed use push, but this legacy class is a little bit of a
design mess – for example, its inappropriate inheritance from Vector
– so it is not necessarily the best example to cite. The signature of
APP DEV WORKSHOP
Stack’s push is also slightly different, returning the newly inserted
element rather than void. Not a terribly useful or common
feature, so one that has been omitted in RecentlyUsedList.
A recently used list is not much use if it is a write-only
collection: you need to get your hands on the contents if you want
to be able to display them. Although drawn from the legacy Vector
interface, the elementAt name has the virtue of being clear in its
intent. The alternative name, found in the Java Collections
API, is the terser and somewhat less intentional get.
Another alternative, again from the Java Collections API,
would be to rename push as add. This name is less specific
because it is supposed to apply to any Collection implementation,
so add is a more neutral term than push for an interface that can
be implemented as a sequence or a set. The following is an
alternative interface that strikes a slightly different balance
between conciseness, consistency and the conventional:
interface RecentlyUsedList
{
boolean isEmpty();
int size();
int capacity();
void clear();
void add(String newHead);
String get(int index);
...
}
If RecentlyUsedList were to be integrated into the Collection
hierarchy, and generalised to handle Object not just String, this
would be the preferred form. However, the form presented first
is more specific and a little clearer in its intent, given the current
scope of the type’s design.
In either case, it is just worth noting that the integer index to
elementAt or get would count from zero and not one. This may
seem obvious, because Java is a zero-based language for array and
collection indexing, but some programmers may be tempted to
start from one because the display presentation of recently used
lists is almost always one based. The representation within the
program should follow the conventions of the language – zero
counting – and should not be coupled to the presentation logic
– one counting.
OK, so these are the considerations that go into expressing the
interface in Java. How about C# or C++? And what about
consistency and completeness within an interface? More on these
questions next time. s
References
1. Butler W Lampson, “Hints for computer system design”,
Operating Systems Review, October 1983.
2. Kevlin Henney, “Sorted”, Application Development Advisor,
July 2003.
3. Bertrand Meyer, Object-Oriented Software Construction,
2nd edition, Prentice Hall, 1997.
4. Joshua Bloch, Effective Java, Addison-Wesley, 2001.
APP DEV WORKSHOP

More Related Content

What's hot

Design pattern
Design patternDesign pattern
Design pattern
Thibaut De Broca
 
Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
Kevlin Henney
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
jinaldesailive
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
Mindfire Solutions
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
Priyanka Pradhan
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
talha ijaz
 
Ooa 1 Post
Ooa 1 PostOoa 1 Post
Ooa 1 Post
Rajesh Kumar
 
C#
C#C#
C# interview questions
C# interview questionsC# interview questions
C# interview questions
Chetan Chaudhari
 
Design patterns
Design patternsDesign patterns
Design patterns
abhisheksagi
 
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
Simplilearn
 
The Grammar of User Experience
The Grammar of User ExperienceThe Grammar of User Experience
The Grammar of User Experience
Stefano Bussolon
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
Shashwat Shriparv
 
C# interview
C# interviewC# interview
C# interview
Thomson Reuters
 
General OOP Concepts
General OOP ConceptsGeneral OOP Concepts
General OOP Concepts
Praveen M Jigajinni
 
Sda 8
Sda   8Sda   8
Bussolon, Betti: Conceptualize once, design anywhere
Bussolon, Betti: Conceptualize once, design anywhereBussolon, Betti: Conceptualize once, design anywhere
Bussolon, Betti: Conceptualize once, design anywhere
Stefano Bussolon
 

What's hot (20)

Design Pattern
Design PatternDesign Pattern
Design Pattern
 
Design pattern
Design patternDesign pattern
Design pattern
 
Something for Nothing
Something for NothingSomething for Nothing
Something for Nothing
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
C# concepts
C# conceptsC# concepts
C# concepts
 
Behavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka PradhanBehavioral pattern By:-Priyanka Pradhan
Behavioral pattern By:-Priyanka Pradhan
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Ooa 1 Post
Ooa 1 PostOoa 1 Post
Ooa 1 Post
 
C#
C#C#
C#
 
C# interview questions
C# interview questionsC# interview questions
C# interview questions
 
Design patterns
Design patternsDesign patterns
Design patterns
 
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
C# Interface | Interfaces In C# | C# Interfaces Explained | C# Tutorial For B...
 
The Grammar of User Experience
The Grammar of User ExperienceThe Grammar of User Experience
The Grammar of User Experience
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
C# interview
C# interviewC# interview
C# interview
 
General OOP Concepts
General OOP ConceptsGeneral OOP Concepts
General OOP Concepts
 
Sda 8
Sda   8Sda   8
Sda 8
 
Bussolon, Betti: Conceptualize once, design anywhere
Bussolon, Betti: Conceptualize once, design anywhereBussolon, Betti: Conceptualize once, design anywhere
Bussolon, Betti: Conceptualize once, design anywhere
 

Similar to Form Follows Function

Stringing Things Along
Stringing Things AlongStringing Things Along
Stringing Things Along
Kevlin Henney
 
If I Had a Hammer...
If I Had a Hammer...If I Had a Hammer...
If I Had a Hammer...
Kevlin Henney
 
Framework Design Guidelines
Framework Design GuidelinesFramework Design Guidelines
Framework Design Guidelines
Mohamed Meligy
 
Tcs NQTExam technical questions
Tcs NQTExam technical questionsTcs NQTExam technical questions
Tcs NQTExam technical questions
AniketBhandare2
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
ansariparveen06
 
Technical_Interview_Questions.pdf
Technical_Interview_Questions.pdfTechnical_Interview_Questions.pdf
Technical_Interview_Questions.pdf
adityashukla939020
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
Sangharsh agarwal
 
The Perfect Couple
The Perfect CoupleThe Perfect Couple
The Perfect Couple
Kevlin Henney
 
Java mcq
Java mcqJava mcq
Java mcq
avinash9821
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
Philip Schwarz
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
nicolbiden
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Featurestechfreak
 
Interfaces & Packages V2
Interfaces & Packages V2Interfaces & Packages V2
Interfaces & Packages V2
Dr Anjan Krishnamurthy
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Raffi Khatchadourian
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
Jagath Bandara Senanayaka
 

Similar to Form Follows Function (20)

Stringing Things Along
Stringing Things AlongStringing Things Along
Stringing Things Along
 
If I Had a Hammer...
If I Had a Hammer...If I Had a Hammer...
If I Had a Hammer...
 
Framework Design Guidelines
Framework Design GuidelinesFramework Design Guidelines
Framework Design Guidelines
 
Stl dich
Stl dichStl dich
Stl dich
 
Tcs NQTExam technical questions
Tcs NQTExam technical questionsTcs NQTExam technical questions
Tcs NQTExam technical questions
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
Technical_Interview_Questions.pdf
Technical_Interview_Questions.pdfTechnical_Interview_Questions.pdf
Technical_Interview_Questions.pdf
 
Intervies
InterviesIntervies
Intervies
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
The Perfect Couple
The Perfect CoupleThe Perfect Couple
The Perfect Couple
 
Stl
StlStl
Stl
 
Java mcq
Java mcqJava mcq
Java mcq
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Interfaces & Packages V2
Interfaces & Packages V2Interfaces & Packages V2
Interfaces & Packages V2
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
 
Csci360 20 (1)
Csci360 20 (1)Csci360 20 (1)
Csci360 20 (1)
 
Csci360 20
Csci360 20Csci360 20
Csci360 20
 

More from Kevlin Henney

Program with GUTs
Program with GUTsProgram with GUTs
Program with GUTs
Kevlin Henney
 
The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical Excellence
Kevlin Henney
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical Development
Kevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
Kevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
Kevlin Henney
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
Kevlin Henney
 
Get Kata
Get KataGet Kata
Get Kata
Kevlin Henney
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
Kevlin Henney
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test Cases
Kevlin Henney
 
Agility ≠ Speed
Agility ≠ SpeedAgility ≠ Speed
Agility ≠ Speed
Kevlin Henney
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
Kevlin Henney
 
Old Is the New New
Old Is the New NewOld Is the New New
Old Is the New New
Kevlin Henney
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-In
Kevlin Henney
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good Name
Kevlin Henney
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Kevlin Henney
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation Quadrant
Kevlin Henney
 
Code as Risk
Code as RiskCode as Risk
Code as Risk
Kevlin Henney
 
Software Is Details
Software Is DetailsSoftware Is Details
Software Is Details
Kevlin Henney
 
Game of Sprints
Game of SprintsGame of Sprints
Game of Sprints
Kevlin Henney
 
Good Code
Good CodeGood Code
Good Code
Kevlin Henney
 

More from Kevlin Henney (20)

Program with GUTs
Program with GUTsProgram with GUTs
Program with GUTs
 
The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical Excellence
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical Development
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
 
Get Kata
Get KataGet Kata
Get Kata
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test Cases
 
Agility ≠ Speed
Agility ≠ SpeedAgility ≠ Speed
Agility ≠ Speed
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Old Is the New New
Old Is the New NewOld Is the New New
Old Is the New New
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-In
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good Name
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation Quadrant
 
Code as Risk
Code as RiskCode as Risk
Code as Risk
 
Software Is Details
Software Is DetailsSoftware Is Details
Software Is Details
 
Game of Sprints
Game of SprintsGame of Sprints
Game of Sprints
 
Good Code
Good CodeGood Code
Good Code
 

Recently uploaded

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
abdulrafaychaudhry
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Pro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp BookPro Unity Game Development with C-sharp Book
Pro Unity Game Development with C-sharp Book
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 

Form Follows Function

  • 1. APP DEV WORKSHOP I T IS OFTEN SAID THAT GOOD DESIGN IS INVISIBLE. What does this mean for something like an interface, which is intentionally a highly visible boundary separating different parts of a system? Interfaces are about communication, both between different components of the system and between the code and the user. A well-designed interface is typically concise, consistent and conventional. Which all sounds a bit dull at first sight, but that is, after all, what it means to be invisible: there is little that is out of the ordinary and little to write home about. Given the significant role that interfaces play in a system – whether we are talking about the interface presented by a header file, a class’s public section, the interface construct found in Java, C#, IDL and other languages, a package’s public section or even a whole API – the “principle of least astonishment” is perhaps one of the most important guidelines to follow: q Concise: Interfaces that try to be helpful by accommodating all possible needs in all possible ways are particularly unhelpful and unaccommodating. An interface should be minimal, but not to the point of being cryptic. The less there is to read, learn and remember, the easier an interface will be to use. q Consistent: An interface that is consistent in its partitioning and naming is easier to anticipate and offers fewer surprises than one that seems to be designed in a fragmented and disconnected fashion, following one style in one part of the interface and another style in a different part of the interface. q Conventional: In selecting names, partitioning method and class responsibility, and organising argument lists and return values, follow established practice where such practice is itself concise and consistent – don’t invent new styles or follow obscure ones unnecessarily, but don’t slavishly follow common but poor forms. An interface that follows the idioms of the language and environment will be more readily grasped than one that does not. Nevertheless, being concise, consistent and conventional is not quite as dull as it first appears: it simply shifts the emphasis and effort of interface design to more weighty matters, and away from the trivial. The use of idioms (expressions and phrasing specific to a cultural grouping) is in contrast to the use of idiolects (affectations of expression peculiar to an individual), wresting responsibility for certain possible, arbitrary variations away from interface designers, and freeing them up to focus on other design issues. The responsibility placed on the designer becomes more one of judgement and breadth of knowledge than one of invention. Signature contracts Interfaces play the role of contracts between different parts of a system1 , and there are many sides to drawing up such a contract2 .The appearance and basic use of an interface constitutes a signature contract: names, types and argument lists. Developers familiar with the contract metaphor often overlook contracts that are not functional contracts, and they often assume that functional contracts are always – and can always – be expressed using only pre- and postconditions3 . Most generally, a contract is an agreement that is binding and typically enforceable, with consequences for any transgression. The use of assertions to enforcecorrectnessofusageandimplementationallows some contractual aspects to be expressed, but it does not cover everything. In statically typed languages, signature contracts tend to be enforced at compile time: incorrect usage leads to a compilation error. In dynamically typed languages, or via reflection, signature contracts are checked at runtime: transgressions are signalled by exceptions.When going through weakly typed interfaces, such as via void * in C, any requirements on a type that are not met will lead to undefined behaviour – a laissez faire enforcement policy with crashing consequences. Style and idiom Consider a simple sorting facility, along the lines discussed in a previous column2 . Narrowing the scope, consider sorting an array or subarray of integers.What would be the most idiomatic way of presenting this facility in C? void sort(int array[], size_t how_many); APP DEV WORKSHOP Defining an interface is more than just putting a front on an implementation. Kevlin Henney looks into the intentional side of interface design Form follows function 38 APPLICATION DEVELOPMENT ADVISOR q www.appdevadvisor.co.uk
  • 2. MARCH–APRIL 2004 39 And in C++? void sort(int *begin, int *end); And in Java? ... public static void sort(int[] array, int from, int to) ... ... In each case the operation is named sort and returns void. However, in spite of the syntactic similarities between the languages, all other details are different. Although it is sometimes possible to adopt one language’s idiom in another, this often leads to an inappropriate look and feel in the borrowing language. The style may work in a technical sense – it compiles and runs – but it may not make the best use of language features or communicate most effectively – it is more idiolectic than idiomatic. For example, although it is possible to adopt the C-style signature for sort in C++, the native C++ approach for expressing algorithms is based on iterator ranges, as used through the Standard Template Library (STL). If the type of the underlying container is generalised to allow any random-access sequence, not just an array, or the type of the elements to be sorted can be anything that can be ordered using the < operator, the sort function generalises directly to the common function template appearance of the STL algorithmic operations: template<typename iterator> void sort(iterator begin, iterator end); Each of the suggested signatures reflects a similar set of capabilities: the ability to take an array of integers and sort all or part of it. In C the subrange is communicated by passing a pointer to the starting element and the count of how many elements after that should be considered, expressed as the standard size_t type, used for denoting sizes, rather than a plain int. This signature takes advantage of C’s close (sometimes too close) relationship between pointers and arrays. By contrast, C++’s notion of subrange is based on an iterator that points to the beginning and one to the first element past the end of the subrange. Java does not allow pointer–array aliasing, so although its signature is similar to the C version, it must name the base of the array explicitly. Java then specifies the subrange using integer indices. Like the C++ version, its range is half-open, i.e. the first index is included in the range but the last is not. An alternative would have been to specify the start followed by the number of elements to be sorted rather than the start and the end indices. However, this is not the convention in common use elsewhere in the Java libraries, so although it has its own merits, those are not enough to outweigh the use of the more idiomatic form. In C and C++ the operation name is global and, in C++, perhaps nested within a namespace. In Java there is no mechanism for defining global operations, so sort needs to be defined in the context of a utility class, which raises new questions. What should be the granularity and scope of such a utility class? A class, Sort, that holds only the single static sort method; a class, Sorting, that holds sort and any related methods, such as an isSorted predicate; a class, named something like ArrayUtilities, that holds sort and other unrelated methods that operate on arrays. The first option is too fine grained and offers no useful room for expansion, with the exception of adding other sort overloads. The third option is the one used by the Java Collections API, and should be avoided as being little more than a coincidental and un-cohesive aggregation of functionality. The second option is probably the wisest in this case. Useful, usable and recently used There were few naming issues in considering the sorting facility: sort was sufficiently concise and conventional. The stylistic concerns were focused mainly on the argument list. Let’s take another example that demonstrates a broader interface to a commonly used facility, but one that is less frequently commoditised than sorting: a recently used list. Application menus often hold a list of the most recently opened documents and modern phones normally hold a list of the most recently dialled numbers. A recently used list is often bounded to an upper capacity.The general behaviour is that of a dispenser type, such as a stack or a priority queue, with the property that the most recently inserted element is found at the front and that an element occurs only once in the whole sequence, i.e. no element is equal to any other element. To keep things simple, rather than focus on holding arbitrary objects that may be mutable and could undermine the uniqueness invariant on the list, just consider the interface to a recently used list that holds strings. What would this look like in Java? interface RecentlyUsedList { boolean isEmpty(); int size(); int capacity(); void clear(); void push(String newHead); String elementAt(int index); ... } This interface follows standard Java capitalisation conventions and uses names found in the Java library. In the Java Collections API the name isEmpty is favoured over the less commonly used empty convention, which would be the appropriate name for such an operation in C++. Notice that the common but rather lame get prefix convention is avoided in naming size and capacity. This prefixing convention is over-applied by many programmers, with the typical effect of making their code look like a form of high-level assembler. Joshua Bloch intentionally avoided this style in the design of much of the Java Collections API 4 , favouring the clearer and more direct adjective style for queries about properties. There is some inconsistency in Java over what to call the size or length query: arrays use a length field; strings use a length method; collections use a size method. As a RecentlyUsedList represents a collection, it makes sense to adopt size.The most related notion to an upper limit is the capacity method found in Vector, which also has the virtue of being a concise name. There is little contention or uncertainty in naming the clear method, which is the conventional form used in Java and other languages. If a recently used list is in some ways like a queue or a stack, common received wisdom suggests that push is the most likely candidate name for the insertion operation. Java’s Stack class does indeed use push, but this legacy class is a little bit of a design mess – for example, its inappropriate inheritance from Vector – so it is not necessarily the best example to cite. The signature of APP DEV WORKSHOP
  • 3. Stack’s push is also slightly different, returning the newly inserted element rather than void. Not a terribly useful or common feature, so one that has been omitted in RecentlyUsedList. A recently used list is not much use if it is a write-only collection: you need to get your hands on the contents if you want to be able to display them. Although drawn from the legacy Vector interface, the elementAt name has the virtue of being clear in its intent. The alternative name, found in the Java Collections API, is the terser and somewhat less intentional get. Another alternative, again from the Java Collections API, would be to rename push as add. This name is less specific because it is supposed to apply to any Collection implementation, so add is a more neutral term than push for an interface that can be implemented as a sequence or a set. The following is an alternative interface that strikes a slightly different balance between conciseness, consistency and the conventional: interface RecentlyUsedList { boolean isEmpty(); int size(); int capacity(); void clear(); void add(String newHead); String get(int index); ... } If RecentlyUsedList were to be integrated into the Collection hierarchy, and generalised to handle Object not just String, this would be the preferred form. However, the form presented first is more specific and a little clearer in its intent, given the current scope of the type’s design. In either case, it is just worth noting that the integer index to elementAt or get would count from zero and not one. This may seem obvious, because Java is a zero-based language for array and collection indexing, but some programmers may be tempted to start from one because the display presentation of recently used lists is almost always one based. The representation within the program should follow the conventions of the language – zero counting – and should not be coupled to the presentation logic – one counting. OK, so these are the considerations that go into expressing the interface in Java. How about C# or C++? And what about consistency and completeness within an interface? More on these questions next time. s References 1. Butler W Lampson, “Hints for computer system design”, Operating Systems Review, October 1983. 2. Kevlin Henney, “Sorted”, Application Development Advisor, July 2003. 3. Bertrand Meyer, Object-Oriented Software Construction, 2nd edition, Prentice Hall, 1997. 4. Joshua Bloch, Effective Java, Addison-Wesley, 2001. APP DEV WORKSHOP