• This repository has been archived on 20/Jul/2020
  • Stars
    star
    240
  • Rank 168,229 (Top 4 %)
  • Language
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Style Guidelines for PayPal Scala Applications

PayPal Scala Style Guidelines

This repository contains style guidelines for writing Scala code at PayPal. Here are our goals for style guides in this repository:

  1. Our style guidelines should be clear.
  2. We all should agree on our style guidelines.
  3. We should change this guideline as we learn and as Scala evolves.
  4. Keep the scalastyle-config.xml in our projects in line with this guide as much as possible.

This repository follows git-flow. If you have a new style guideline, open a pull request against develop. We'll discuss in the PR comments. The official guidelines live in master

Whitespace

  • Use two spaces for indentation.
  • Add a newline to the end of every file.

Line Length

  • Use a maximum line length of 160 characters.

Names

Functions, Classes and Variables

Use camel case for all function, class and variable names. Classes start with an upper case letter, and values and functions start with a lower case. Here are some examples:

class MyClass {
  val myValue = 1
  def myFunction: Int = myValue
}

Acronyms

Use camel case for acroynms, for example, HttpUtil. For consistency, this includes class names like Ttl and Json as well as common terms such as Db and Io. Follow normal camel-casing rules.

val httpIoJsonToXmlParser = new HttpIoJsonToXmlParser()

Package Objects

Package names should be all lowercase with no underscores.

File names for package objects must match the most specific name in the package. For example, for the com.paypal.mypackage package object, the file should be named mypackage.scala and the file should be structured like this:

package com.paypal

package object mypackage {
  //...
}

Classes

Public Methods

Limit the number of public methods in your class to 30.

Throwables

  1. Prefer non-case classes when defining exceptions and errors unless you plan on pattern matching on the exception.
  2. If providing a cause is desirable and not mandatory then define it as an option. Note, the use of .orNull.
class CrazyException(msg: String, cause: Option[Throwable] = None) extends Exception(msg, cause.orNull)
class SuperCrazyError(msg: String, cause: Option[Throwable] = None) extends Error(msg, cause.orNull)

Imports

Ordering

IntelliJ's code style configuration allows for automatic grouping of imports by namespace. We use the following ordering, which you should add to your IntelliJ configuration (found in Preferences > Code Style > Scala):

java
___blank line___
scala
___blank line___
akka
spray
all other imports
___blank line___
com.ebay
com.paypal

You should also regularly run IntelliJ's Optimize Imports (Edit > Optimize Imports) against your code before merging with develop, to maintain import cleanliness.

Location

Most imports in a file should go at the top, right below the package name. The only time you should break that rule is if you import some or all names from an object from inside a class. For example:

package mypackage

import a.b.c.d
import d.c.b.a

class MyClass {
  import Utils._
  import MyClassCompanion.A
}

object MyClassCompanion {
  case class A()
}

object Utils {
  case class Util1()
  case class Util2()
}

Predef

Never import anything inside of Scala's 'Predef' object. It is automatically imported for you, so it's redundant to manually import. IntelliJ will often try to import it, so be aware.

Values

Use val by default. vars should be limited to local variables or private class variables. Their usage should be well documented, including any considerations that developers must make with respect to concurrency.

One common usage of vars will be inside of Akka Actors. Here's an example of that usage:

class MyActor extends Actor {
  //This is local state to the actor that represents the current sum of all integers it has received.
  //It must be marked private and never accessed outside of the processing of a single message, to ensure
  //that it's concurrency safe. Additionally, don't acquire a lock before you access this variable.
  //Doing so might block message processing unnecessarily. If you follow all of these rules related to concurrency,
  //you shouldn't need a lock anyway.
  private var sum: Int = 0

  override def receive: Receive {
    case i: Int => sum = sum + 1
  }
}

Modifiers

Optional variable modifiers should be declared in the following order: override access (private|protected) final implicit lazy.

For example,

private implicit lazy val someSetting = ...

Functions

Rules to follow for all functions:

  • Always put a space after : characters in function signatures.
  • Always put a space after , in function signatures.

Public Functions

All public functions and methods, including those inside objects must have:

  • A return type
  • Scaladoc including a function overview, information on parameters, and information on the return value. See the Scaladoc section for more details.

Here is a complete example of a function inside of an object.

object MyObject {
  /**
   * returns the static integer 123
   * @return the number 123
   */
  def myFunction: Int = {
    123
  }
}

Parameter Lists

If a function has a parameter list with fewer than 70 characters, put all parameters on the same line:

def add(a: Int, b: Int): Int = {
  ...
}

If a function has long or complex parameter lists, follow these rules:

  1. Put the first parameter on the same line as the function name.
  2. Put the rest of the parameters each on a new line, aligned with the first parameter.
  3. If the function has multiple parameter lists, align the opening parenthesis with the previous one and align parameters the same as #2.

Example:

def lotsOfParams(aReallyLongParameterNameOne: Int,
                 aReallyLongParameterNameTwo: Int,
                 aReallyLongParameterNameThree: Int,
                 aReallyLongParameterNameFour: Int)
                (implicit adder: Adder,
                 reader: Reader): Int = {
  ...
}

For function names over 30 characters, try to shorten the name. If you can't, start the parameter list on the next line and indent everything 2 spaces:

def aVeryLongMethodThatShouldHaveAShorterNameIfPossible(
  aParam: Int,
  anotherParam: Int,
  aThirdParam: Int)
 (implicit iParam: Foo,
  bar: Bar): String = {
  ...
}

In all cases, the function's return type still has to be written directly following the last closing parenthesis.

Calling Functions

When calling functions with numerous arguments, place the first parameter on the same line as the function and align the remaining parameters with the first:

fooBar(someVeryLongFieldName,
       andAnotherVeryLongFieldName,
       "this is a string",
       3.1415)

For functions with very long names, start the parameter list on the second line and indent by 2 spaces:

aMuchLongerMethodNameThatShouldProbablyBeRefactored(
  aParam,
  anotherParam,
  aThirdParam)

It's your choice whether to place closing parenthesis directly following the last parameter or on a new line (in "dangling" style).

You can do this:

aLongMethodNameThatReturnsAFuture(
  aParam,
  anotherParam,
  aThirdParam
).map { res =>
  ...
}

Or this:

aLongMethodNameThatReturnsAFuture(
  aParam,
  anotherParam,
  aThirdParam).map { res =>
  ...
}

Anonymous functions

Anonymous functions start on the same line as preceding code. Declarations start with { (note the space before and after the {). Arguments are then listed on the same line. A few more notes:

  • Do not use braces after the argument list, just start the function body on the next line.
  • Argument types are not necessary. You should use them if it makes the code clearer though.

Here's a complete example example:

Option(123).map { number =>
  println(s"the number plus one is: ${number + 1}")
}

Exceptions to the Rule

Use parentheses and an underscore for anonymous functions that are:

  • single binary operations
  • a single method invocation on the input
  • two or fewer unary methods on the input

Examples:

val list = List("list", "of", "strings")
list.filter(_.length > 2)
list.filter(_.contains("i"))

Passing named functions

If the function takes a single argument, then arguments and underscores should be omitted.

For example:

Option(123).map(println)

is preferred over

Option(123).map(println(_))

Calling functions

Prefer dot notation except for these specific scenarios:

  1. Specs2 matchers
  2. Akka pipeTo, !, ?

For example:

Option(someInt).map(println)

is preferred over

Option(someInt) map println
Rule Exceptions

Java <=> Scala interoperation on primitives: Scala and Java booleans, for example, are not directly compatible, and require an implicit conversion between one another. Normally this is handled automagically by the Scala compiler, but the following code would reveal a compiler error:

Option(true).foreach(someMethodThatTakesAJavaBoolean)

A named parameter is not necessary to achieve this. An underscore should be used to resolve the implicit conversion. To avoid confusion, please also add a note that a Scala <=> Java conversion is taking place:

Option(true).foreach(someMethodThatTakesAJavaBoolean(_))  // lol java

Logic Flows

In general, logic that handles a choice between two or more outcomes should prefer to use match.

Match Statements

When you match on any type, follow these rules:

  1. Pattern matching should be exhaustive and explicitly handle the failure/default case rather than relying on a runtime MatchError. (This is specific to match blocks and not case statements in partial functions.) Case classes used in pattern matching should extend a common sealed trait so that compiler warnings will be generated for inexhaustive matching.
  2. Indent all case statements at the same level, and put the => one space to the right of the closing )
  3. Short single line expressions should be on the same line as the case
  4. Long single line and multi-line expressions should be on the line below the case, indented one level from the case.
  5. Do not add extra newlines in between each case statement.
  6. Filters on case statements should be on the same line if doing so will not make the line excessively long.

Here's a complete example:

Option(123) match {
  case Some(i: Int) if i > 0 =>
    val intermediate = doWorkOn(i + 1)
    doMoreWorkOn(intermediate)
  case _ => 123
}

Option

Flows with Option values should be constructed using the match keyword as follows.

def stuff(i: Int): Int = { ... }

Option(123) match {
  case None => 0
  case Some(number) => stuff(number)
}

The .fold operator should generally not be used. Simple, single-line patterns are acceptable for .fold, such as:

def stuff(i: Int): Int = { ... }

Option(123).fold(0)(stuff)

Similarly, simple patterns are acceptable for .map with .getOrElse, such as:

def stuff(i: Int): Int = { ... }

Option(123).map(stuff).getOrElse(0)

You should enforce expected type signatures, as match does not guarantee consistent types between match outcomes (e.g. the None case could return Int, while the Some case could return String).

When creating Options, use .opt. If the value is a constant, use .some instead.

val doThisForConstants = "hello".some
val notThisForConstants = "goodbye".opt

val doThisForEverythingElse = foo().opt
val notThisForEverythingElse = bar().some

For Comprehension

For comprehensions should generally not be wrapped in parentheses in order to recover, flatMap, etc. Instead, separate the for comprehension into its own variable and perform additional operations on that.

val userAddress = for {
  address <- loadAddress()
} yield address

userAddress.recover {
  // recover from loadAddress exception
}.flatMap {
  // pull info from address, etc.
}

In addition, if performing additional operations on the result of the yield as part of the result of the for comprehension itself, code should be separated by braces and begin on a newline. For example:

for {
  address <- loadAddress() // returns Option
} yield {
  address match {
    case Some(s) => ...
    case None => ...
  }
}

Akka

Ask and Tell

Prefer ! and ? over .tell and .ask.

someActor1 ! msg
someActor2 ? msg

is preferred over

someActor1.tell(msg)
someActor2.ask(msg)

Tests

Write your tests using Specs2. Each specification is a single class that extends Specification. Put each specification into its own file. Inside each specification, follow these rules:

  • create a single trait inside your Specification class that extends CommonImmutableSpecificationContext (from Cascade.) Most people name this trait Context.
  • Group tests into classes, case classes or objects at your discretion.
  • All of your grouped test classes, case classes and objectss should go inside your specification class and should extend your Context trait
  • All methods inside your test classes should be wrapped with apply. When you do so, CommonImmutableSpecificationContext will execute before and after hooks automatically.
  • Your tests execute concurrently by default. Only change them to execute sequentially for a good reason, and document that reason in comments.

Here's an example of the above rules in code:

class MyTest extends Specification { override def is = s2"""
  add(1, 2) should equal 3 ${Add().equals3()}
  """

  trait Context extends CommonImmutableSpecificationContext

  case class Add() extends Context {
    def equals3 = apply {
      add(1, 2) must beEqualTo(3)
    }
  }
}

Scaladoc, Comments, and Annotations

All classes, objects, traits, and methods should be documented. Generally, follow the documentation guidelines provided by the Scala Documentation Style Guide on ScalaDoc.

Rules:

  • Classes that are instantiated via methods in a companion object must include ScalaDoc documentation with a code example.
  • Abstract classes should be documented with an example of their intended implementation.
  • Implicit wrapper classes must include ScalaDoc documentation with a code example.
  • Public, protected, and package-private methods must include ScalaDoc documentation.
  • Private methods should be documented, however it is left to the discretion of the developer as to the level of documentation.
  • All methods must include @throws annotations if they throw an exception in their normal operation.

Use your best judgment otherwise, and err toward more documentation rather than less.

Further Reading

Several of these recommendations are adapted from the Scala Documentation Style Guide, including Declarations and Indentation. The guidelines presented in this document should supersede all other style recommendations.

More Repositories

1

glamorous

DEPRECATED: 💄 Maintainable CSS with React
JavaScript
3,640
star
2

junodb

JunoDB is PayPal's home-grown secure, consistent and highly available key-value store providing low, single digit millisecond, latency at any scale.
Go
2,565
star
3

accessible-html5-video-player

Accessible HTML5 Video Player
JavaScript
2,451
star
4

react-engine

a composite render engine for universal (isomorphic) express apps to render both plain react views and react-router views
JavaScript
1,449
star
5

squbs

Akka Streams & Akka HTTP for Large-Scale Production Deployments
Scala
1,433
star
6

PayPal-node-SDK

node.js SDK for PayPal RESTful APIs
JavaScript
1,279
star
7

paypal-checkout-components

please submit Issues about the PayPal JS SDK here: https://github.com/paypal/paypal-js/issues
JavaScript
1,270
star
8

gatt

Gatt is a Go package for building Bluetooth Low Energy peripherals
Go
1,135
star
9

PayPal-iOS-SDK

Accept credit cards and PayPal in your iOS app
Objective-C
974
star
10

gnomon

Utility to annotate console logging statements with timestamps and find slow processes
JavaScript
932
star
11

PayPal-Android-SDK

Accept PayPal and credit cards in your Android app
Java
824
star
12

bootstrap-accessibility-plugin

Accessibility Plugin for Bootstrap 3 and Bootstrap 3 as SubModule
HTML
789
star
13

PayPal-Python-SDK

Python SDK for PayPal RESTful APIs
Python
702
star
14

AATT

Automated Accessibility Testing Tool
JavaScript
601
star
15

PayPal-Ruby-SDK

Ruby SDK for PayPal RESTful APIs
Ruby
593
star
16

ipn-code-samples

PHP
561
star
17

seifnode

C++
545
star
18

PayPal-NET-SDK

.NET SDK for PayPal's RESTful APIs
C#
535
star
19

PayPal-Java-SDK

Java SDK for PayPal RESTful APIs
Java
535
star
20

data-contract-template

Template for a data contract used in a data mesh.
460
star
21

Checkout-PHP-SDK

PHP SDK for Checkout RESTful APIs
PHP
418
star
22

hera

High Efficiency Reliable Access to data stores
Go
289
star
23

SeLion

Enabling Test Automation in Java
Java
281
star
24

nemo-core

Selenium-webdriver based automation in node.js
JavaScript
261
star
25

support

An evented server framework designed for building scalable and introspectable services, built at PayPal.
Python
261
star
26

PayPal-Cordova-Plugin

PayPal SDK Cordova/Phonegap Plugin
Objective-C
248
star
27

gimel

Big Data Processing Framework - Unified Data API or SQL on Any Storage
Scala
245
star
28

merchant-sdk-php

PHP SDK for integrating with PayPal's Express Checkout / MassPay / Web Payments Pro APIs
PHP
230
star
29

paypal-js

Loading wrapper and TypeScript types for the PayPal JS SDK
TypeScript
229
star
30

paypal-rest-api-specifications

This repository contains the specification files for PayPal REST APIs.
192
star
31

resteasy-spring-boot

RESTEasy Spring Boot Starter
Java
188
star
32

Checkout-Java-SDK

PayPal Checkout Java SDK
Java
182
star
33

autosklearn-zeroconf

autosklearn-zeroconf is a fully automated binary classifier. It is based on the AutoML challenge winner auto-sklearn. Give it a dataset with known outcomes (labels) and it returns a list of predicted outcomes for your new data. It even estimates the precision for you! The engine is tuning massively parallel ensemble of machine learning pipelines for best precision/recall.
Python
171
star
34

skipto

SkipTo is a replacement for your old classic "Skipnav" link. Once installed on a site, the script dynamically determines the most important places on the page and presents them to the user in a drop-down menu.
HTML
152
star
35

TLS-update

Documentation & tools for the upcoming TLSv1.2 required update
Java
148
star
36

Checkout-NET-SDK

.NET SDK for Checkout RESTful APIs
C#
139
star
37

cascade

Common Libraries & Patterns for Scala Apps @ PayPal
Scala
129
star
38

merchant-sdk-ruby

Ruby
110
star
39

heap-dump-tool

Tool to sanitize data from Java heap dumps.
Java
110
star
40

NNAnalytics

NameNodeAnalytics is a self-help utility for scouting and maintaining the namespace of an HDFS instance.
Java
110
star
41

paypal-smart-payment-buttons

Smart Payment Buttons
JavaScript
108
star
42

yurita

Anomaly detection framework @ PayPal
Scala
106
star
43

InnerSourceCommons

DEPRECATED - old repo for InnerSourceCommons website. Moved to https://github.com/InnerSourceCommons/innersourcecommons.org
JavaScript
105
star
44

adaptivepayments-sdk-php

PHP SDK for integrating with PayPal's AdaptivePayments API
PHP
101
star
45

fullstack-phone

A dual-module phone number system with dynamic regional metadata ☎️
JavaScript
90
star
46

sdk-core-php

for classic PHP SDKs.
PHP
87
star
47

paypal-here-sdk-android-distribution

Add credit card (swipe & key-in) capabilities to your Android app
Java
84
star
48

merchant-sdk-dotnet

C#
83
star
49

paypal-here-sdk-ios-distribution

Add credit card (tap, insert, swipe & key-in) capabilities to your iOS app
Objective-C
82
star
50

payflow-gateway

Repository to store the Payflow Gateway and PayPal Payments Pro SDKs.
C#
80
star
51

sdk-packages

Binary packages for deprecated SDKs.
77
star
52

android-checkout-sdk

Kotlin
77
star
53

Iguanas

Iguanas is a fast, flexible and modular Python package for generating a Rules-Based System (RBS) for binary classification use cases.
Jupyter Notebook
74
star
54

paypal-android

One merchant integration point for all of PayPal's services
Kotlin
72
star
55

legalize.js

JavaScript object validation for browsers + node
JavaScript
70
star
56

paypalcheckout-ios

Need to add Native Checkout to your iOS Application? We can help!
Ruby
70
star
57

paypal-sdk-client

Shared config for PayPal/Braintree client SDKs
JavaScript
65
star
58

load-watcher

Load watcher is a cluster-wide aggregator of metrics, developed for Trimaran: Real Load Aware Scheduler in Kubernetes.
Go
63
star
59

dce-go

Docker Compose Executor to launch pod of docker containers in Apache Mesos.
Go
63
star
60

merchant-sdk-java

Java SDK for integrating with PayPal's Express Checkout / MassPay / Web Payments Pro APIs
Java
62
star
61

sdk-core-java

for classic Java SDKs.
Java
61
star
62

paypal-ios

One merchant integration point for all of PayPal's services
Swift
59
star
63

gorealis

Version 1 of a Go library for interacting with the Aurora Scheduler
Go
58
star
64

scorebot

CSS
57
star
65

PPExtensions

Set of iPython and Jupyter extensions to improve user experience
Python
50
star
66

paypal-checkout-demo

Demo app for paypal-checkout
JavaScript
49
star
67

dione

Dione - a Spark and HDFS indexing library
Scala
49
star
68

Payouts-PHP-SDK

PHP SDK for Payouts RESTful APIs
PHP
49
star
69

pdt-code-samples

Visual Basic
48
star
70

butterfly

Application transformation tool
Java
47
star
71

Payouts-NodeJS-SDK

NodeJS SDK for Payouts RESTful APIs
JavaScript
47
star
72

digraph-parser

Java parser for digraph DSL (Graphviz DOT language)
Java
44
star
73

paypalhttp_php

PHP
43
star
74

tech-talks

Place for all PayPalX presentations, tech talks, and tutorials, and the sample code and apps used in those.
ColdFusion
38
star
75

Illuminator

iOS Automator
Swift
38
star
76

paypal-sdk-release

Unified SDK wrapper module for tests, shared build config, and deploy
JavaScript
37
star
77

PayPal-REST-API-issues

Issue tracking for REST API bugs, features, and documentation requests.
37
star
78

paypal-messaging-components

PayPal JavaScript SDK - messaging components
JavaScript
37
star
79

ionet

ionet is a bridge between the Go stdlib's net and io packages
Go
37
star
80

paypal-access

Examples and code for PayPal Access
Python
36
star
81

horizon

An SBT plugin to help with building, testing, analyzing and releasing Scala
Scala
35
star
82

Payouts-Java-SDK

Java SDK for Payouts RESTful APIs
Java
35
star
83

genio

Genio is an extensible tool that can generate code to consume APIs in multiple programming languages based on different API specification formats.
Ruby
35
star
84

mirakl-hyperwallet-connector

The Hyperwallet Mirakl Connector (HMC) is a self-hosted solution that mediates between a Mirakl marketplace solution and the Hyperwallet (PayPal) payout platform.
Java
34
star
85

openapilint

Node.js linter for OpenAPI specs
JavaScript
31
star
86

paypal-sdk-constants

JavaScript
27
star
87

sdk-core-ruby

Core Library for PayPal Ruby SDKs
Ruby
27
star
88

go.crypto

Go crypto packages
Go
26
star
89

PayPal-PHP-SDK

PHP SDK for PayPal RESTful APIs
PHP
26
star
90

nemo-view

View interface for the Nemo automation framework
JavaScript
26
star
91

Gibberish-Detector-Java

A small program to detect gibberish using a Markov Chain
Java
26
star
92

nemo-accessibility

Automate Accessibility testing within your environment (Localhost)
JavaScript
25
star
93

Payouts-Python-SDK

Python SDK for Payouts RESTful APIs
Python
25
star
94

here-sideloader-api-samples

Sideloader API samples that enable to integrate PayPal Here into other apps
Objective-C
24
star
95

couchbasekafka

Couchbase Kafka Adapter
Java
24
star
96

baler

Bundle assets into iOS static libraries
Python
22
star
97

invoice-sdk-php

PHP SDK for integrating with PayPal's Invoicing API
PHP
21
star
98

Payouts-DotNet-SDK

DotNet SDK for Payouts RESTful APIs
C#
20
star
99

paypal-funding-components

PayPal JavaScript SDK Funding Components
JavaScript
20
star
100

squbs-scala-seed.g8

Scala giter8 Template for Squbs
Scala
20
star