Recent Posts
Archives

Posts Tagged ‘BestPractices’

PostHeaderIcon [KotlinConf2019] Putting Down the Golden Hammer: Pragmatic Kotlin with Huyen Tue Dao

Learning a new programming language, especially one as rich and expressive as Kotlin, often comes with the temptation to use every new feature and syntactic sugar—the “golden hammer”—everywhere. Huyen Tue Dao, a prominent Android developer then known for her work at Trello and her insightful contributions to the Kotlin community, addressed this phenomenon at KotlinConf 2019. Her talk, “Putting Down the Golden Hammer,” shared valuable lessons learned from nearly three years of full-time Kotlin development, emphasizing the importance of pragmatism, readability, and maintainability over merely clever code. Huyen’s insights can often be found on her blog, randomlytyping.com.

Huyen began by acknowledging the allure of Kotlin’s advanced features. While these constructs can be powerful and lead to concise code, she cautioned that their overuse or misuse can sometimes negatively impact code clarity and long-term maintainability. The journey of a developer learning Kotlin often involves an initial phase of enthusiasm for these new tools, followed by a more mature understanding of when and how to apply them judiciously.

The Evolution of a Kotlin Developer’s Approach

Huyen Tue Dao shared her personal evolution in approaching various Kotlin features. She reflected on how code written early in her Kotlin journey might look different from her current practices, shaped by experience, trial, and error. This evolution is natural and signifies a deeper understanding of the language’s nuances and the trade-offs involved in different coding styles.

One key area she touched upon (common in such discussions) is the balance between conciseness and readability. Kotlin allows for very compact code, but sometimes a slightly more verbose approach can be easier for others (and one’s future self) to understand and maintain. She stressed that while Kotlin’s features are designed to make developers more productive, this productivity should not come at the expense of creating code that is difficult to reason about or debug. The goal should be to write “better Kotlin,” which implies code that is not only functionally correct and efficient but also clear, pragmatic, and maintainable.

Pragmatism in Feature Usage: Scope Functions, Nullability, and More

Huyen Tue Dao delved into specific Kotlin features and utilities, discussing both their “fun and shiny” aspects and how they can be overused or even abused. For instance, scope functions (let, run, with, apply, also) are powerful tools for executing a block of code within the context of an object. However, excessive nesting or unclear usage can lead to code that is hard to follow. Huyen advocated for intentionality: choosing the right scope function for the task and ensuring its use enhances clarity rather than obscuring it.

Null safety is another cornerstone of Kotlin, designed to prevent NullPointerExceptions. Huyen discussed the importance of being deliberate about nullability. While Kotlin’s type system helps manage nulls effectively, developers still need to make conscious decisions about whether a type should be nullable and handle nullable types appropriately, without resorting to excessive safe calls (?.) or non-null asserted calls (!!) that might hide underlying design issues. She emphasized being clear about why something is nullable and documenting such decisions when necessary, especially when assumptions about nullability change or when interacting with APIs where null safety guarantees might be different.

Towards Readable and Maintainable Kotlin

Ultimately, Huyen Tue Dao’s message was a call for mindful Kotlin development. She encouraged the audience to revel in Kotlin’s wonderful syntax and features but to always keep readability, maintainability, and pragmatism at the forefront. Understanding the underlying implementation of certain features can also be crucial to avoid potential performance issues.

The aim is not to write code that merely feels “sexy and Kotlin-y” but to craft solutions that are robust, easy for a team to work with, and stand the test of time. Recognizing the potential pitfalls of overusing certain constructs and consciously choosing simpler, clearer alternatives when appropriate leads to what Huyen termed “even better and even more fun Kotlin”. Her talk served as a valuable reminder that true mastery of a language lies not just in knowing its features, but in knowing when and how to use them wisely.

Links:

PostHeaderIcon [ScalaDaysNewYork2016] Nightmare Before Best Practices: Lessons from Failure

At Scala Days New York 2016, José Castro, a software engineer at Codacy, delivered a riveting presentation that diverged from the typical conference narrative. Instead of showcasing success stories, José shared cautionary tales of software development mishaps, emphasizing the critical importance of adhering to best practices to prevent costly errors. Through vivid anecdotes, he illustrated how neglecting simple procedures can lead to significant financial and operational setbacks, offering valuable lessons for developers.

The Costly Oversight in Payment Systems

José Castro began with a chilling account of a website launch that initially seemed successful but resulted in a €180,000 loss. The development team had integrated a shopping cart with a bank’s payment system, but for three weeks, no customer payments were processed. José recounted how a developer’s personal purchase revealed that the system was authorizing transactions without completing charges, a flaw unnoticed due to inadequate testing. The bank’s policy allowed only one week to finalize charges, rendering earlier transactions uncollectible. This oversight, José emphasized, could have been prevented with rigorous integration testing and automated checks to ensure payment flows were correctly implemented.

Deployment Disasters and Human Error

Another tale José shared involved a deployment error that brought down a critical system for 12 hours. A developer, tasked with updating a customer-facing application, accidentally deployed to the production environment instead of staging, overwriting essential configurations. The absence of proper deployment protocols and environment safeguards exacerbated the issue, leading to significant downtime. José highlighted the need for automated deployment pipelines and environment-specific configurations to prevent such human errors, ensuring that production systems remain insulated from untested changes.

The Perils of Inadequate Documentation

José also recounted a scenario where insufficient documentation led to a prolonged outage in a payment processing system. A critical configuration change was made without updating the documentation, leaving the team unable to troubleshoot when the system failed. This lack of clarity delayed recovery, costing the company valuable time and revenue. José advocated for documentation-driven development, where comprehensive records of system configurations and procedures are maintained, enabling quick resolution of issues and reducing dependency on individual knowledge.

Fostering a Healthy Code Review Culture

In addressing code review challenges, José discussed the emotional barriers developers face when receiving feedback. He shared an example of a team member who successfully separated personal ego from code quality, embracing constructive criticism. To mitigate conflicts, José recommended automated code review tools like Codacy, which provide objective feedback, reducing interpersonal tension. By automating routine checks, teams can focus on higher-level implementation discussions, fostering a collaborative environment and improving code quality without bruising egos.

Links:

PostHeaderIcon [DevoxxFR2012] JavaServer Faces: Identifying Antipatterns and Embracing Best Practices for Robust Applications

Lecturer

Kito Mann leads as Principal Consultant at Virtua, Inc., focusing on enterprise architecture, training, and mentoring in JavaServer Faces (JSF), HTML5, portlets, Liferay, and Java EE. Editor-in-chief of JSFCentral.com, he co-hosts the Enterprise Java Newscast and hosts the JSF Podcast series. Author of “JavaServer Faces in Action” (Manning), Kito participates in JCP expert groups for CDI, JSF, and Portlets. An international speaker at events like JavaOne and JBoss World, he holds a BA in Computer Science from Johns Hopkins University.

Abstract

This article probes Kito Mann’s exploration of common pitfalls in JavaServer Faces (JSF) development, juxtaposed with recommended strategies for optimal performance and maintainability. It scrutinizes real-world antipatterns, from hardcoded IDs and database accesses in getters to broader issues like inconsistent standards and improper API usage. Embedded in JSF’s component-based framework, the analysis reviews techniques for dependency injection, state management, and view optimization. Via code illustrations and case studies, it evaluates consequences for scalability, team onboarding, and application longevity, advocating principled approaches to harness JSF’s strengths effectively.

Common Pitfalls in Component and Bean Management

JSF’s strength lies in its reusable components and managed beans, yet misuse breeds inefficiencies. Kito identifies hardcoding IDs in backing beans as a cardinal error—components autogenerate IDs, risking conflicts. Instead, employ bindings or relative references.

Database operations in getters exacerbate performance: invoked multiple times per request, they overload servers. Solution: Fetch data in lifecycle methods like init() or use lazy loading:

@PostConstruct
public void init() {
    users = userService.getUsers();
}

Lack of standards fragments codebases; enforce conventions for naming, structure. Wrong APIs, like FacesContext in non-UI layers, violate separation—inject via CDI.

Optimizing State and View Handling

State management plagues JSF: View-scoped beans persist unnecessarily if not destroyed properly. Kito advises @ViewScoped with careful serialization.

Large views bloat state; mitigate with for partial renders or for modularization. c:if toggles subtrees but beware quirks—prefer rendered attributes unless tree pruning is essential.

Dependency lookups in getters repeat calls; leverage CDI injection:

@Inject
private UserProvider userProvider;

This ensures singletons are fetched once, enhancing efficiency.

Enhancing Performance Through Best Practices

Ajax integrations demand caution: Overuse swells requests. Optimize with execute/render attributes.

Navigation rules clutter; use implicit navigation or bookmarkable views with GET parameters.

Testing antipatterns include neglecting UI tests—employ JSFUnit or Selenium for comprehensive coverage.

Implications: These practices yield responsive, scalable apps. By avoiding antipatterns, teams reduce debugging, easing onboarding. In enterprise contexts, they align JSF with modern demands like mobile responsiveness.

Kito’s insights empower developers to refine JSF usage, maximizing framework benefits.

Links: