This document discusses interface design principles and provides examples of interface signatures in different programming languages.
The key principles discussed are that interfaces should be concise, consistent, and conventional. They should follow established conventions and idioms of the given language to be intuitive for developers.
Examples are given of interface signatures for a sorting function in C, C++ and Java. While the core functionality is the same, the signatures differ based on language idioms and features. Defining interfaces properly considers the language conventions rather than just technical correctness.
User centered design assumes that a research phase with a representative sample of the final users should be the basis for the definition of the functional and soft requirements of a project. How can we translate the results of the ux research into actionable requirements?
In my talk, I wish to give you some suggestions on how to informally analyse the verbal results of the ux research to identify the schemata, the ontologies, the taxonomies and the functions of your application.
User centered design assumes that a research phase with a representative sample of the final users should be the basis for the definition of the functional and soft requirements of a project. How can we translate the results of the ux research into actionable requirements?
In my talk, I wish to give you some suggestions on how to informally analyse the verbal results of the ux research to identify the schemata, the ontologies, the taxonomies and the functions of your application.
These are some of the FAQ's that are asked in TCS NQT exam. By preparing these questions you can obtain good marks.
NOTE: These are FAQ's don't completely relay on it.
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. In this talk, I will first overview several new, key features of Java 8 that can help make programs easier to read, write, and maintain, especially in regards to collections. These features include Lambda Expressions, the Stream API, and enhanced interfaces, many of which help bridge the gap between functional and imperative programming paradigms and allow for succinct concurrency implementations. Next, I will discuss several open issues related to automatically migrating (refactoring) legacy Java software to use such features correctly, efficiently, and as completely as possible. Solving these problems will help developers to maximally understand and adopt these new features thus improving their software.
Presented at .NET South West (2024-03-26)
https://www.meetup.com/dotnetsouthwest/events/299766807/
One of the greatest shifts in modern programming practices has been how programmers across many different domains, languages and environments have embraced unit testing. Good unit testing, however, is more than waving NUnit at your C# source. Tests help to make long-term product development cost effective rather than a cost centre, they underpin the effective flow of CI/CD and reduce failure demand on a team.
But the discussion of unit testing goes further than simply writing tests: what makes a good unit test? It is not enough to have tests; poor quality tests can hold back development just as good tests can streamline it. This session provides a perspective on what good unit tests (GUTs) can look like with a couple of examples.
Presented at Agile meets Architecture (2023-10-05)
Video at https://www.youtube.com/watch?v=LLEXAdO3X1o
One of the (most overlooked) principles of the Manifesto for Agile Software Development is that "Continuous attention to technical excellence and good design enhances agility". All too often, work that focuses on addressing technical issues is deprioritised in the name of focusing on business value.
Is there a case for technical excellence — in code, in architecture, in people — beyond its appearance on a might-as-well-be-hidden page on a manifesto that's over two decades old? Is technical excellence only the concern of technical roles? Is a good architecture in conflict with business value or a vehicle for it?
This session looks to go beyond buzzwords to build a case for technical excellence that appeals to all roles in a development organisation, noting that "The best architectures, requirements, and designs emerge from self-organizing teams".
Presented online for Build Stuff meetup (https://www.buildstuff.events/events/online-build-stuff-meetup-with-kevlin-henney-and-cassandra-faris)
Whether we are talking about software architecture, coding practices or our development process, it's important to keep it real. All too often we find ourselves attracted to ideas that sound great in theory, but may not work out in practice. All too often we assume we are right — the planned release schedule, the key architectural decisions, the good practices we saw in a blog — but fail to adjust for reality. We fail to acknowledge that our knowledge was incomplete or that the situation has changed, sticking to the plan and practice regardless.
In this talk we will look at what an empirical approach to development means in practice, why it is that up-front architecture is risky and expensive, why it is that most teams who say they're doing agile development are not, and how we can use uncertainty and instability to structure our time and our code.
Presented online for C++ on Sea (2020-07-17)
Video at https://www.youtube.com/watch?v=Bai1DTcCHVE
Lambdas. All the cool kid languages have them. But does lambda mean what C++ and other languages, from Java to Python, mean by lambda? Where did lambdas come from? What were they originally for? What is their relationship to data abstraction?
In this session we will into the history, the syntax, the uses and abuses of lambdas and the way in which lambda constructs in C++ and other languages do (or do not) match the original construct introduced in lambda calculus.
Presented online for javaBin (2020-04-14)
Video at https://www.youtube.com/watch?v=orcSUE0Jjdc
Lambdas. All the cool kid languages have them. But does ‘lambda’ mean what Java, JavaScript, etc. mean by ‘lambda’? Where did lambdas come from? What were they originally for? What is their relationship to data abstraction?
In this session we will look into the history, the syntax and the uses of lambdas and the way in which lambda constructs in Java and other languages do (or do not) match the original construct introduced in lambda calculus.
Presented at DevSum (2018-05-31)
The SOLID principles are often presented as being core to good code design practice. Each of S, O, L, I and D do not, however, necessarily mean what programmers expect they mean or are taught. By understanding this range of beliefs we can learn more about practices for objects, components and interfaces than just S, O, L, I and D.
This talk reviews the SOLID principles and reveals contradictions and different interpretations. It is through paradoxes and surprises we often gain insights. We will leave SOLID somewhat more fluid, but having learnt from them more than expected.
Presented at Foo Café (2019-03-21)
Video at https://www.youtube.com/watch?v=tLSKLLxrZyY
Programmers use coding katas to kick the tyres of their programming languages, paradigms and practices. Typically anchored in a TDD cycle, katas are simple problems that give programmers the opportunity to exercise deliberate practice and explore different approaches, whether programming style, pair programming or test-first programming.
But the simplicity can be deceptive, with many programmers tiring of these katas too soon, missing out on some of the more mind-bending and paradigm-expanding opportunities on offer.
This session will pick on a couple of katas and dig deeper into TDD, lambdas, language(s), (dys)functional programming and Alcubierre drive. It will present code in a variety of languages, highlight the weaknesses of some common mantras, play around with ideas — and blend code, humour and general nerdiness to be both an enjoyable and educational session.
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
Presented at ACCU Conference 2018 (2018-04-12)
Video at https://www.youtube.com/watch?v=mrY6xrWp3Gs
When programmers describe code as 'procedural', it’s generally not meant as a compliment. There is a belief that we have collectively moved pass such thinking and onto better paradigms. But a paradigm is no more than a pattern language, a family of solutions fit for a context. Change the kind of problem you are solving and you may find a different solution makes sense — even, in these days where pure functions battle it out with classy objects, procedural programming.
This talk takes a look at some of the past, present and future of procedural programming, looking at how there’s more to it than many first assume, how it has informed and continues to influence language design and how it relates to other paradigms, such as functional and OO.
Structure and Interpretation of Test CasesKevlin Henney
Presented at ACCU Cambridge (2018-10-23)
Throw a line of code into many codebases and it's sure to hit one or more testing frameworks. There's no shortage of frameworks for testing, each with their particular spin and set of conventions, but that glut is not always matched by a clear vision of how to structure and use tests — a framework is a vehicle, but you still need to know how to drive. The computer science classic, Structure and Interpretation of Computer Programs, points out that "Programs must be written for people to read, and only incidentally for machines to execute". The same is true of test code.
This talk takes a deep dive into unit testing, looking at examples and counterexamples across a number of languages and frameworks, from naming to nesting, exploring the benefits of data-driven testing, the trade-offs between example-based and property-based testing, how to get the most out of the common given–when–then refrain and knowing how far to follow it.
Keynote present at Agile Tour Vienna (2018-10-06)
Velocity. Sprints. More points, more speed. An obsession with speed often overtakes the core values of agile software development. It’s not just development of software; it’s development of working software. Sprints are not about sprinting; they’re about sustainable pace. Time to market is less important than time in market. Full-stack development is normally a statement about technology, but it also applies to individuals and interactions. The full stack touches both the code and the world outside the code, and with that view comes responsibility and pause for thought. Doing the wrong thing smarter is not smart. The point of a team is its group intelligence not its numbers. Is scaling up the challenge, or is scaling down the real challenge? The distraction and misuse of speed, velocity, point-based systems, time, team size, scale, etc. is not the accelerant of agile development. Agility lies in experimentation, responsiveness and team intelligence.
Keynote presented at NewCrafts (2018-06-18)
Video available at https://vimeo.com/276832516
It has been said that immutability changes everything. But what does that mean in practice? What does it mean for existing code that looks more like the mutant apocalypse than an elegant application of mathematical thinking? Immutability can be an ideal that is hard to reach. Refactoring, on the other hand, is all about the art of the possible. In this talk we'll be clarifying motivation and exploring some approaches to help reducing state mutability in code.
Keynote presented at GOTO Chicago (2018-04-26)
Video available at https://www.youtube.com/watch?v=AbgsfeGvg3E
Everything is changing. Everything is new. Frameworks, platforms and trends are displaced on a weekly basis. Skills are churning.
And yet... Beneath this seemingly turbulent flow there is a slow current, strong and steady, changing relatively little over the decades. Concepts with a long history appear in new forms and fads and technologies. Principles are revisited. Ideas once lost to the mainstream are found again.
In this keynote we revisit the present through the past, looking at the enduring principles that shape programming languages, architecture, development practice and development process, the ideas that cycle round, each time becoming perhaps a little better defined, a little more mature, and look to see what else might be on the horizon.
Presented at SwanseaCon (2017-09-26)
We default to considering systems from an insider's perspective; the view from outside can be quite different. Can we apply this inversion to more than just requirements?
We may say we want testing, but what do we want from testing? We may say we want logging, but what do we want from logging? We may say we want clean code, but what do we want from clean code? We may say we want an agile process, but what do we want from an agile process? These are harder questions, but their answers can make for better solutions.
Presented at .NET South West (2017-07-25)
Code is basically made up of three things: names, spacing and punctuation. With these three tools a programmer needs to communicate intent, and not simply instruct. But if we look at most approaches to naming, they are based on the idea that names are merely labels, so that discussion of identifier naming becomes little more than a discussion of good labelling.
A good name is more than a label; a good name should change the way the reader thinks. A good name should describe structure with intention, as opposed to the affix-heavy approach common to many naming conventions in current use, where the addition of more prefixes and suffixes becomes homeopathic, diluting the meaning. Good naming is part of good design. This session looks at why and what it takes to get a good name.
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
Presented at code::dive (2016-11-15)
Video available at https://www.youtube.com/watch?v=brfqm9k6qzc
It is all to easy to dismiss problematic codebases on some nebulous idea of bad practice or bad programmers. Poor code, however, is rarely arbitrary and random in its structure or formulation. Systems of code, well or poorly structured, emerge from systems of practice, whether effective or ineffective. To improve code quality, it makes more sense to pick apart the specific practices and see their interplay — the cause — than to simply focus on the code itself — the effect. This talk looks at how a handful of coding habits, design practices and assumptions can systematically balloon code and compound its accidental complexity.
Thinking Outside the Synchronisation QuadrantKevlin Henney
Presented at code::dive (2016-11-16)
Video available at https://www.youtube.com/watch?v=yl25p91flLY
Ask programmers what comes to mind when you say concurrency and most are likely to say threads. Ask what comes to mind when you say threads and most are likely to say locks or synchronisation. These assumptions are so deeply held that they define and constrain how programmers are taught and think about concurrency: thread safety is almost synonymous with the avoidance of race conditions and the guarded protection of mutable state. But this is only one quadrant of four possibilities, a quadrant diagram partitioned by mutable–immutable along one axis and shared–unshared along another. Modern C++ supports programmers in all four quadrants, not just the synchronisation quadrant. From immutability to actors, this talk will take a look at patterns and practices that encourage thinking and coding outside the locked box.
Presented at GOTO Amsterdam (2017-06-13)
Video available at https://www.youtube.com/watch?v=YyhfK-aBo-Y
What is risk? Many people aren't sure, but it's not just uncertainty: risk is exposure to uncertainty.
Instead of just plastering over the cracks, security should also involve reducing the size and number of cracks, reducing the opportunities for cracks to appear, reducing the class of errors and oversights that can open a system to failure instigated from the outside. We can learn a lot from other kinds of software failure, because every failure unrelated to security can be easily reframed as a security-failure opportunity.
This is not a talk about access control models, authentication, encryption standards, firewalls, etc. This is a talk about reducing risk that lives in the code and the assumptions of architecture, reducing the risk in development practices and in the blind spot of development practices.
Keynote presented at SATURN (2nd May 2017)
Video available at https://www.youtube.com/watch?v=MS3c9hz0bRg
"It's just a detail." Have you ever said that or been told that? Whether it's about implementation or requirements, we often use the word detail to suggest that something is not important enough to worry about. There are so many things to worry about in software development that we need to prioritize—too much detail, not enough focus. The problem is that in software, the details matter because that is what software is: lots of details brought together in combination. If we don't focus on the details, we get debt, defects, and delays.
Presented at Agile Bath & Bristol (21st March 2017)
If software development is a co-operative game, as Alistair Cockburn observed, then what kind of game is Scrum? Lots of people are playing it — or say they are — but there seems to be some disagreement about what the point of the game is, how to play it and even, in many cases, what the rules are. This talk looks at Scrum and other agile approaches through the lens of nomic games, hypothesis-driven development and fun.
Presented at the European Bioinformatics Institute (17th March 2017)
We often talk about good code — that we would like to write it, that there isn't enough of it, that it should not be considered an optional attribute of a codebase. We often talk about it but, when it comes to being precise, we don't always agree what constitutes good code, nor do we necessarily share a common view on its value.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
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