If Switch Statements breaks SOLID Principles as Uncle Bob states (in Clean Code), should I be using them at all with OO Languages? [duplicate] - swift

This question already has answers here:
Large Switch statements: Bad OOP?
(14 answers)
Switch statements are bad? [closed]
(8 answers)
Closed 5 years ago.
In Clean Code, Uncle Bob states that switch statements almost always break Single Responsibility and Open/Closed Principles. So does this mean that I should rarely (the only case he proposes is when switch is buried in an Abstract Factory to create polymorphic objects) use Switch Statements and therefore Enumerations? This brings the question that are Switch Statements really necessary to have in an OO Language?
Swift language for instance seems to favour enumerations (they can carry data and so on). Minimising their usage would be a major decision. Swift being an OO Language, do the same rules apply?

Related

Do tagless algebra needs laws? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I read the wonderful blog from JOHN A DE GOES regarding to tagless final. In the section 5.Fake Abstraction, he has mentioned:
Unfortunately, these operations satisfy no algebraic laws—none
whatsoever! This means when we are writing polymorphic code, we have
no way to reason generically about putStrLn and getStrLn.
For all we know, these operations could be launching threads, creating
or deleting files, running a large number of individual side-effects
in sequence, and so on.
He is correspond to the following tagless algebra:
trait Console[F[_]] {
def putStrLn(line: String): F[Unit]
val getStrLn: F[String]
}
Does it mean, writting laws for tageless algebra is not possible or do I misunderstand something.
A few things:
John A De Goes, while is very knowledgeable has also a lot of opinions and express them as if they were inferred from mathematics without making a clear distinction - this posts is a part of series where he basically pitches that tagless final is often a bad solution and ZIO is a good one
paragraph says that tagless final often doesn't follow algebraic laws which means that we cannot e.g. consider IO monid/semigroup and similar. Which is true. But it doesn't mean that these constructs cannot obey some contracts (called laws) because the do and that is the whole point of Cats Effect
nobody can force you to write laws for algebras, because laws are basically some particular way of writing specification/tests where you write a separate test for some class of interfaces and then for every implementation you can instantiate this test to check if your implementation fulfill contracts - and yes, nobody can force you to write test for your code. However, that can be said about virtually everything we code, and TTFI give you benefit of making it easier to specify a common behavior of widely different implementations, and then writing your code and tests carefully, sticking to the part of contract that is vital for a particular piece of code while also making these dependencies on contracts explicit
So yes, nobody can force you to write laws for your algebras, but people who implement them in libraries actually do this, and if you write your own algebras, you are encouraged to do so, so this argument is stretched and eristic.

What is the primary technical challenge that Scala's implicit solves? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
While learning Scala, I found the concept of implicit difficult to rationalize. It allows one to pass values implicitly, without explicitly mentioning them.
What is its purpose for being and what is the problem that it seeks to solve?
At it's heart, implicit is a way of extending the behavior of values of a type in a way that's fully controllable on a local level in your program, and external to the original code that defines those values. It's one approach to solving the expression problem.
It lets you keep your core classes focused on their most fundamental structure and behavior, and factor out higher-level behaviors. It's used to achieve ad hoc polymorphism, where two formally unrelated data types can be seamlessly adapted to the same interface, so that they can be treated as instances of the same type.
For example, rather than your data model classes containing JSON serialization behavior, you can store that behavior elsewhere, and implicitly augment an object with the ability to serialize itself. This amounts to defining in an implicit instance, which specifies how your object can be viewed as "JSON serializable", rather than its original type, and it's done without editing real type of the object.
There are several forms of implicit, which are pretty thoroughly covered elsewhere. Use cases include enhance-my-library pattern, the typeclass pattern, implicit conversions, and dependency injection.
What's really interesting to me, in the context of this question, is how this differs from approaches in other languages.
Enhance-my-library and typeclasses
In many other languages, you accomplish this by monkey patching (typically where there is no type checking) or extension methods. These approaches have the downside of composing unpredictably and applying globally. In statically typed languages without a way of opening classes, you usually have to make explicit adapters. This has the downside of a lot of boilerplate. In both static and dynamic languages, you may also be able to use reflection, but usually with a lot of ceremony and complexity.
In Haskell, typeclasses exist as a first-class concept. They're global, though, so you don't get the local control over what typeclass is applied in a given situation. In Scala, you control what implicits are in scope locally, through the modules you import. And you can always opt out of implicit resolution entirely by passing parameters explicitly.
People advocate for global versus local resolution of typeclasses one way or the other, depending on who you ask.
Implicit conversions
A lot of other languages have no way to accomplish this. But it's become pretty frowned upon in Scala, so maybe this is for good reason.
There's a paper about type classes with older slides and discussion.
Being able implicitly to pass an object that encodes a type class simplifies the boilerplate.
Odersky just responded to a critique of implicits that
Scala would not be Scala if it did not have implicit parameters and
classes.
That suggests they solve a challenge that is central to the design of the language. In other words, supporting type classes is not an ancillary concern.
Its a deep question really It is something that is very powerful and you can use them to write abstract code eg typeclasses etc i can recommend some tutorials that you may look into and then we can haved a chat maybe sometime :)
It is all about providing sensible defaults in your code.
Also the magic of invoking apparently non existent methods on objects which just seems to work! All that good stuff is done via implicits.
But for all its power it may cause people to write some really bad code as well.
Please do watch Nick Partridge's presentation here and i am sure if you code along with him you will understand why and how to approach implicits.
Watch it here
Dick Walls excellent presentation with live coding
Watch both parts.

Scala code as data [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“eval” in Scala
Dr. Subramaniam in his presentation http://www.youtube.com/watch?v=LH75sJAR0hc at min 30 when he starts talking about functional style in Scala he gives this example
class Car {
def turn(direction: String) = {
println("turning " + direction)
}
}
val car = new car
car turn "left"
and then he says that the last line could be read from a data file and evaluated. So, data becomes code, code becomes data.
How does Scala supports this? Does it have an eval function?
Pretty much every language supports an eval function (even strongly, statically typed languages like Haskell). Many language runtimes built for languages that are primarily implemented via bytecode interpretation (such as Lisp-like languages, Erlang or Java) support the ability to insert new (byte)code at runtime.
Once you can insert new code dynamically, you can write eval.
Scala is an example of such a language, where the JVM is available at runtime.
Even in language implementations without specific support for full meta-programming, or even dynamic linking, there are often ways to dynamically generate code under programmer control, either via reflection mechanisms or code generation support libraries (such as LLVM).
Beyond just a simple one-stage eval, more generally, languages that support multi-stage computation allow for generation of programs from one stage to the next, for arbitrary numbers of stages, making it possible to safely, arbitrarily nest evals.
Background reading
McCarthy, John, History of LISP, SIGPLAN Not. 1978. -- introduces eval

Why does objective C does not support overloading? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Why Objective-C doesn't support method overloading?
I was going through this link which has the answer to my question. But I was not able to understand what the right guy is trying to say. It will be really great if someone can simplify and provide an explanation.
In C++ the compiler has type information and can choose between several methods based on the types. To do the same in Objective C it would have to be done at run-time, because the compiler knows little about object types due to the dynamic nature of the language (i.e. all objects are of type id). While this seems possible, it would be very inefficient in practice.
I think it's a historical artifact. Objective-C is derived from C and Smalltalk, and neither of them support overloading.
If you want overloading, you can use Objective-C++ instead. Just name your sources with the ".mm" extension instead of just ".m".
Just be careful to be sure you know what you are doing if you mix C++ and Objective-C idioms. For example Objective-C exceptions and C++ exceptions are two completely different animals and cannot be used interchangeable.
What he is trying to say is that method overloading is not possible with dynamic typed languages since in dynamic typed languages the information about each of the object is not known until run time. In a statically typed during compile time the overloading can be resolved. You will just create the same functions with same names but the compiler would have enough information to resolve the ambiguity between various calls which it gets. But in dynamic typed languages since the objects are resolved only during run time it is not possible to resolve between the various calls.

What is the purpose of Scala programming language? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
It is my opinion that every language was created for a specific purpose. What was Scala created for and what problems does it best solve?
One of the things mentioned in talks by Martin Odersky on Scala is it being a language which scales well to tackle various problems. He wasn't talking about scaling in the sense of performance but in the sense that the language itself can seem to be expanded via libraries. So that:
val lock = new ReentrantReadWriteLock
lock withReadLock {
//do stuff
}
Looks like there is some special syntactic sugar for dealing with j.u.c locks. But this is not the case, it's just using the scala language in such a way as it appears to be. The code is more readable, isn't it?
In particular the various parsing rules of the scala language make it very easy to create libraries which look like a domain-specific language (or DSL). Look at scala-test for example:
describe("MyCoolClass") {
it("should do cool stuff") {
val c = new MyCoolClass
c.prop should be ("cool")
}
}
(There are lots more examples of this - I found out this one yesterday). There is much talk about which new features are going in the Java language in JDK7 (project coin). Many of these features are special syntactic sugar to deal with some specific issue. Scala has been designed with some simple rules that mean new keywords for every little annoyance are not needed.
Another goal of Scala was to bridge the gap between functional and object-oriented languages. It contains many constructs inspired (i.e. copied from!) functional languages. I'm thing of the incredibly powerful pattern-matching, the actor-based concurrency framework and (of course) first- and higher-order functions.
Of course, your question said that there was a specific purpose and I've just given 3 separate reasons; you'll probably have to ask Martin Odersky!
One more of the original design goals was of course to create a language which runs on the Java Virtual Machine and is fully interoperable with Java classes. This has (at least) two advantages:
you can take advantage of the ubiquity, stability, features and reputation of the JVM. (think management extensions, JIT compilation, advanced Garbage Collection etc)
you can still use all your favourite Java libraries, both 3rd party and your own. If this wasn't the case, it would be a significant obstacle to using Scala commercially in many cases (mine for example).
Agree with previous answers but recommend the Introduction to An Overview of the Scala Programming Language:
The work on Scala stems from a research effort to develop better language support for component software. There are two hypotheses that we would like to validate with the Scala experiment. First, we postulate that a programming language for component software needs to be scalable in the sense that the same concepts can describe small as well as large parts. Therefore, we concentrate on mechanisms for abstraction, composition, and decomposition rather than adding a large set of primitives which might be useful for components at some level of scale, but not at other levels. Second, we postulate that scalable support for components can be provided by a programming language which unifes and generalizes object-oriented and functional programming. For statically typed languages, of which Scala is an instance, these two paradigms were up to now largely separate. (Odersky)
I'd personally classify Scala alongside Python in terms of which problems it solves and how. The conspicuous difference and occasional complaint is Type complexity. I agree Scala's abstractions are complicated and at times seemingly convoluted but for a few points:
They're also mostly optional.
Scala's compiler is like free testing and documentation as cyclomatic complexity and lines of code escalate.
When aptly implemented Scala can perform otherwise all but impossible operations behind consistent and coherent APIs. From Scala 2.8 Collections:
For instance, a String (or rather: its backing class RichString) can be seen as a sequence of Chars, yet it is not a generic collection type. Nevertheless, mapping a character to character map over a RichString should again yield a RichString, as in the following interaction with the Scala REPL:
scala> "abc" map (x => (x + 1).toChar)
res1: scala.runtime.RichString = bcd
But what happens if one applies a function from Char to Int to a string? In that case, we cannot produce a string as result, it has to be some sequence of Int elements instead. Indeed one gets:
"abc" map (x => (x + 1))
res2: scala.collection.immutable.Vector[Int] = Vector(98, 99, 100)
So it turns out that map yields different types depending on what the result type of the passed function argument is! (Odersky)
Since it's functional and uses actors (as I understand it, please comment if I've got this wrong) it makes it very easy to scale nearly anything up to any number of CPUs.
That said, I see Scala as kind of a test bed for new language features. Throw in the kitchen sink and see what happens.
My personal opinion is that for any apps involving a team of more than 3 people you are more productive with a language with Very Simple and Restrictive Syntax just because the entire job becomes more how you interact with others as opposed to just coding to make the computer do something.
The more people you add, the more time you are going to spend explaining what ?: means or the difference between | and || as applied to two booleans (In Java, you'll find very few people know).