ForgetSou | Blog

❤ 武统台湾 刻不容缓 ❤

0%

App架构-编程语言、面向对象思想

App架构-编程语言、面向对象思想

Soul&Sword

如果只会一门编程语言,无论多么精通,仍然显得不够优秀。

在我们进行APP开发过程中要把握好以下几点:抓中心、看本质、重思想。

2.1 编程语言

2.1.1 Swift

Swift是Apple 2014年编程的编程语言,已支持 Android NDK。

下图是java和swift对比。

img

2.1.2 Optional

Swift中引用了Optional,可以理解为一种新的类型,很好地解决了OC的“nil or not nil”问题,Java 8也用了Optional。Optional的核心思想是采用契约式编程思想(如断言),将问题显性的呈现出来。

我们可以通过查看源码,了解Swift Optional的定义(Swift/Stdlib/Public/Core/Optional.Swift),其本质是一个枚举,包含none和some(Wapped)两个case,分别代表可选类型“有值”和“无值”两种情况。

@frozen public enum Optional  : ExpressibleByNilLiteral {
/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none

/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)

/// Creates an instance that stores the given value.
public init(_ some: Wrapped)

/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `map` method with a closure that returns a non-optional value.
/// This example performs an arithmetic operation on an
/// optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let possibleSquare = possibleNumber.map { $0 * $0 }
/// print(possibleSquare)
/// // Prints "Optional(1764)"
///
/// let noNumber: Int? = nil
/// let noSquare = noNumber.map { $0 * $0 }
/// print(noSquare)
/// // Prints "nil"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable public func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?

/// Evaluates the given closure when this `Optional` instance is not `nil`,
/// passing the unwrapped value as a parameter.
///
/// Use the `flatMap` method with a closure that returns an optional value.
/// This example performs an arithmetic operation with an optional result on
/// an optional integer.
///
/// let possibleNumber: Int? = Int("42")
/// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in
/// let (result, overflowed) = x.multipliedReportingOverflow(by: x)
/// return overflowed ? nil : result
/// }
/// print(nonOverflowingSquare)
/// // Prints "Optional(1764)"
///
/// - Parameter transform: A closure that takes the unwrapped value
/// of the instance.
/// - Returns: The result of the given closure. If this instance is `nil`,
/// returns `nil`.
@inlinable public func flatMap<U>(_ transform: (Wrapped) throws -> U?) rethrows -> U?

/// Creates an instance initialized with `nil`.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// initialize an `Optional` instance with a `nil` literal. For example:
///
/// var i: Index? = nil
///
/// In this example, the assignment to the `i` variable calls this
/// initializer behind the scenes.
public init(nilLiteral: ())

/// The wrapped value of this instance, unwrapped without checking whether
/// the instance is `nil`.
///
/// The `unsafelyUnwrapped` property provides the same value as the forced
/// unwrap operator (postfix `!`). However, in optimized builds (`-O`), no
/// check is performed to ensure that the current instance actually has a
/// value. Accessing this property in the case of a `nil` value is a serious
/// programming error and could lead to undefined behavior or a runtime
/// error.
///
/// In debug builds (`-Onone`), the `unsafelyUnwrapped` property has the same
/// behavior as using the postfix `!` operator and triggers a runtime error
/// if the instance is `nil`.
///
/// The `unsafelyUnwrapped` property is recommended over calling the
/// `unsafeBitCast(_:)` function because the property is more restrictive
/// and because accessing the property still performs checking in debug
/// builds.
///
/// - Warning: This property trades safety for performance. Use
/// `unsafelyUnwrapped` only when you are confident that this instance
/// will never be equal to `nil` and only after you've tried using the
/// postfix `!` operator.
@inlinable public var unsafelyUnwrapped: Wrapped { get }

/// Returns a Boolean value indicating whether an argument matches `nil`.
///
/// You can use the pattern-matching operator (`~=`) to test whether an
/// optional instance is `nil` even when the wrapped value's type does not
/// conform to the `Equatable` protocol. The pattern-matching operator is used
/// internally in `case` statements for pattern matching.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type, and then uses a `switch`
/// statement to determine whether the stream is `nil` or has a configured
/// value. When evaluating the `nil` case of the `switch` statement, this
/// operator is called behind the scenes.
///
/// var stream: DataStream? = nil
/// switch stream {
/// case nil:
/// print("No data stream is configured.")
/// case let x?:
/// print("The data stream has \(x.availableBytes) bytes available.")
/// }
/// // Prints "No data stream is configured."
///
/// - Note: To test whether an instance is `nil` in an `if` statement, use the
/// equal-to operator (`==`) instead of the pattern-matching operator. The
/// pattern-matching operator is primarily intended to enable `case`
/// statement pattern matching.
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to match against `nil`.
public static func ~= (lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool

/// Returns a Boolean value indicating whether the left-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if stream == nil {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
public static func == (lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool

/// Returns a Boolean value indicating whether the left-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if stream != nil {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A value to compare to `nil`.
/// - rhs: A `nil` literal.
public static func != (lhs: Wrapped?, rhs: _OptionalNilComparisonType) -> Bool

/// Returns a Boolean value indicating whether the right-hand-side argument is
/// `nil`.
///
/// You can use this equal-to operator (`==`) to test whether an optional
/// instance is `nil` even when the wrapped value's type does not conform to
/// the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` is
/// `nil`.
///
/// var stream: DataStream? = nil
/// if nil == stream {
/// print("No data stream is configured.")
/// }
/// // Prints "No data stream is configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
public static func == (lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool

/// Returns a Boolean value indicating whether the right-hand-side argument is
/// not `nil`.
///
/// You can use this not-equal-to operator (`!=`) to test whether an optional
/// instance is not `nil` even when the wrapped value's type does not conform
/// to the `Equatable` protocol.
///
/// The following example declares the `stream` variable as an optional
/// instance of a hypothetical `DataStream` type. Although `DataStream` is not
/// an `Equatable` type, this operator allows checking whether `stream` wraps
/// a value and is therefore not `nil`.
///
/// var stream: DataStream? = fetchDataStream()
/// if nil != stream {
/// print("The data stream has been configured.")
/// }
/// // Prints "The data stream has been configured."
///
/// - Parameters:
/// - lhs: A `nil` literal.
/// - rhs: A value to compare to `nil`.
public static func != (lhs: _OptionalNilComparisonType, rhs: Wrapped?) -> Bool

}

2.1.3 Java 和 Swift核心语法对比

img

下面我们对比下Java/Guava和Swift中对Optional的使用,最终发现Java和Guava非常相似。

  • 初始化
Optional xx= Optional.empty(); // java8

Optional xx= Optional.absent(); // guava

var xx: XX?; // guava
  • 创建对象
// java8
Optional<Integer> xx = Optional.of (12);Optional<Integer> xx = Optional.ofNullable(null);

// guava
Optional<Integer> = Optional.of(12);

Optional<Integer> = Optional.fromNullable(null);

// Swift
var xx: Int? = 12

var xx: Int?
  • 是否存在
//  java
if (xx.isPresent()) {}

// guava

if (xx.isPresent()) {}

// swift
if let xx= xx {)

2.2 面向对象思想

2.2.1 编程范式(Programming Paradigm)

编程范式是编程语言的一种分类,并不是针对哪种具体编程语言,一种语言也可以适用多种编程范式。

编程范式/编程范型,是指从事软件工程的一种典型的编程风格(可以对照方法学),例如,函数式编程、面向对象编程等为不同的编程范式。

常见的编程范式有过程化(命令化)编程、事件驱动编程、面向对象编程及函数式编程等。

  • 过程化(命令式)编程。如将机器/汇编语言、BASIC、C、ForTRAN等支持过程化的编程范式的编程语言归纳为过程是编程语言,特别适合解决现行的算法问题,属于典型的程序流程思想。

  • 事件驱动编程。结合图形用户界面(GUI)编程应用。

  • 面向对象编程(OOP)。面向对象的基本概念–封装、继承、多态,通过类、方法、对象和消息传递,来支持面向对象的程序设计范式,Java和C++都是面向对象的编程语言。

  • 函数编程。函数编程是一种结构化编程,其核心思想是把运算过程尽量携程一些列嵌套的函数调用,在代码建解读、代码管理、并发编程上更加便捷,这是继OO之后越来越火热的一种编程范式。

  • 面向切向编程(AOP)。AOP可以认为是函数式编程的一种衍生范型,利用AOP可以对业务逻辑的各个部分进行隔离,使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,从而提高开发效率。

2.2.2 封装、继承和多态

OO


个人博客: 🏡 ForgetSou


-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道