Scala code style and conventions [closed] - java

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 7 years ago.
Improve this question
I am familiar with "Scala coding styles and conventions?"
I also have read this article which states that a programmer is able to produce only so many lines of code per day and therefore a language with a "better" syntax can only help in this direction.
As there is nothing perfect in the world, the syntax of Scala has its disadvantages (of course someone can see these as pure advantages). I am talking about stuff like:
def someMethod(someParameter: Int): Boolean = {
// import here in the middle of nowhere
import com.example.bad.VeryBad._
// semicolon here? maybe?
val two = 1+1;
// nested function here
def boo(a: Int) = a+1;
// now do something useful
println(boo(two))
// for God's sake don't use return!!!
two == 2
}
If one has Java background (or even C++, C#, etc.) it is kind of weird to have import statements in the middle of a function, to have nested functions and I am not even going into other language constructs.
I am a bit sceptical about the real productivity gain coming with Scala. How do you experience this? Do you apply all (as much as possible) of the coding conventions and is this a real benefit? Is there a better way to wrap ones head around this style of code?
P.S. maybe this whole post can be moved to Programmers or similar...

I can share only my experience and I don't know whether other people's experiences are similar. It certainly depends on personal preferences.
Imports in blocks
I came to Scala from Java, so my preference in general is to have all imports at the top of the file. This makes it easier for me to faster see the dependencies of the files. Sometimes however I do use local import in places where I want to import a name only locally and not to pollute the namespace of the whole file.
Semicolons
After few weeks in Scala I really enjoy the the lack of mandatory semicolons. In Scala they are mostly not needed, but they can be helpful when you want to write more short statements on one line. Scala actually changes my attitude towards semicolons and now in new projects I don't use semicolons even in JavaScript.
Nested functions
This is one of the best features of Scala: Functional programming. It allows to write much simpler code consisting of small easily understandable functions working with immutable data. This decreases the complexity of the code, reduces bugs and increases the productivity.
Returns
Again, lack of return statements feels just natural. The function returns the value of its expression, where the value of a sequence of statements/expressions is the last one of them. Return statements just feel very unnatural in Scala.
Productivity
Scala has a learning curve and of course when I have started my productivity had a dent caused by my lack of familiarity with the language and the standard library. Now, after few months of Java and Scala work, I can say that I am in more productive in Scala than in Java. Even though I consider myself a Java expert but only a Scala novice.

I'll go step by step, although some points could be subject to personal opinion:
Imports:
there are some cases where this is pretty useful, for example to shorten you code in case of constants:
object Constants { val someConstant = "123" }
def someMethod(someParameter: Int): Boolean = {
import Constants._
doSomething(someConstant)
}
this also gives the reader a hint on where is that someConstant coming from, having it in the top declaration can be not so explicit.
Semicolon: nobody uses them in scala, the only useful application which comes to mind is if you want to write multiple statement in one line
val a = 1; val b= 2
Not that useful in the end.
Nested methods: these are perfectly fine, wether you should use it or not vary on your use case, also there are around many example of recursive or tail recursive functions which use nested methods.
There's no need to use return, I've never seen it used in my experience plus it can be quite confusing in some cases.

Using such imports for implicits is useful in many cases.
For this usage, importing makes code safer and more readable.
Second case would be ambiguous class and package names (can be solved via aliases). Showing explicite which one is using can be helpful.
In Scala you can do many things in many ways, a little bit like with C++. You have more responsibility for your coding style. Watch this: https://www.youtube.com/watch?v=kkTFx3-duc8&feature=share
Nested methods are great for recurrence and when such method should not be used even as private at class level. With nesting you can also reduce amount of passed arguments.
If you can you then you should place you nested methods on the top of method body. Giving comments on where is constructor body at big class is also helpful.
Scala gives to community the ability to develop the language, scala can change in fundamental ways due to our experiments, good practices.

Related

The best way to use three-valued logic variables [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 6 years ago.
Improve this question
I'm looking for the best way to implement three-valued logic.
I googled and found three different approaches:
Use null value for Boolean variable as undefined
This variant looks to dangerous for me because it can unexpectedly cause NullPointerException
Use Optional<Boolean> type
This variant still is a bit dangerous. To avoid NoSuchElementException you should use constructions like this:
Optional<Boolean> amIRight = Optional.empty();
if (Optional.of(true).equals(amIRight ) {
doSome();
}
It looks too wordy for me
Implement your own enum
The last variant seems to be the best. Almost safe, very simple in undefstanding. But I haven't find any of such enums in widely spread java libriaries such as Apache, Google Guava and so on. It looks strange for me everybody avoids the simpler and safest implementation.
May be I missed something and there are serious reason not to implement three-valued logic enum.
If enum works for you, go for it.
Don't use that Boolean, it is ugly and destroy readability ... I also can't imagine how horrible it would be if you want it to support 4 values later...
Other cautions / advise :
Are you sure that you will use only 3 values?
In many situation, design tends to change, and enum will be no longer enough.
Using a class that encapsulate enum (or int) can provide better flexibility.
However, you can change from enum to class later.
In my program, I extensively use enum.
You shouldn't care much about what popular libraries do, just pick the best that work for you!
About the very interesting hypothesis :
... there are serious reason not to implement three-valued logic enum. ...
Suppose that I am Java language designer.
You ask for a 3-logic enum.
I accept you proposal.
Then, Mr.2D ask "We have 3-logic enum. Why don't you provide 4-logic enum to support +x -x +y -y?".
I give him what he want.
After that, Mr.LoveFive Mr.ObsessiveSick ..... I think you got the point.
There has to be a threshold (when to stop) and the demand for 3-enum is relatively very low compared to 2-enum (boolean).
I agree that enums is by far the safest and best solution to your problem. Perhaps enums are not widely used in projects like Apache because enums are relatively new in Java (I think they came along in Java 1.5).
If you want 3 valued logic, you are no longer talking about simple true/false conditions, you are talking about a state machine. Arguably state machines are among the most powerful paradigms in programming. If you aren't conversant with automata theory, look it up.

Is there a possibility that C++ multiple inheritance might be replaced with the Java interfaces? [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 8 years ago.
Improve this question
I have been studying a bit of Java and C++ more or less at the same time and I noticed that Java has a more friendly and intuitive way of interpreting the OOP than the C++ way.
Yes, Java is completely OO and, on the other hand, C++ supports many paradigms, but this doesn't mean that C++ couldn't improve its way of implementing the OO paradigm.
C++ supports multiple inheritance and Java translated it with multiple implementation (interfaces), which I find really intuitive and simple (I don't think that this is just an opinion).
My first question is in the title. I think that C++ would be more friendly, without losing practically a bit of its power. It's a question of improving a extraordinary programming language, which however is not perfect.
My second question is: what are the advantages of multiple inheritance compared to the interfaces of Java programming language (if any)?
Multiple inheritance can be dangerous, but it's sometimes the most appropriate solution to a problem, and there's lots of software already written that uses it. Removing multiple inheritance from C++ would break all that software, in a way that's not simple to fix. Being compatible with existing code is more important than being "friendly".
If you want the effect of a Java interface in C++, just write a class that contains nothing but pure-virtual member functions, and derive from it using virtual inheritance to "implement" it in another class.
Java was designed as a higher-level and simpler language than C++, and the tradeoffs between them are the same as between any high-level and lower-level language. Java provides a bit less flexibility (e.g. single inheritance, little control over memory allocation) in exchange for being a bit easier to work with; C++ provides more power and flexibility at the cost of having to "know what you're doing" a bit more. These differences are OK; there's no need to turn one language into the other.
C++ is becoming more and more user-friendly with the updates, becoming bit by bit more like java, but it needs not to change too much not to wreck legacy code. The Boost library is more or less the pioneer of the c++ language, being the (probably) most used library of all times and taking an easier and more intuitive OO approach to c++. Features from the Boost libraries often get to the STD eventually.
Let's take this easy example : class man and class parent have respective functions work and cry. class dad inherits from both man and parent. Now you don't have to write cry twice when you write class mom which inherits from class woman as well as from parent.
1.Having multiple inheritance in a explicit way is seems to be more user friendly but actually it is not. There are lot of problem will be coming in the future if you do that i mean in your project for an instance knowingly unknowingly you will be adding the same code again and again to your final Class which makes your project more complicated and confuses the interpreter which method should be executed at the appropriate time.
Just consider in C++ you have
Class A
{
void display_a(){}
}
Class B A
{
void display_b(){}//this class contains 'display_a()' too
}
Class C A,B //multiple inheritance.
{
display_c(){} //this class contains two times 'display_a()' and one time 'display_b()'
}
so class a contains two times 'display_a()' this is the problem we have in multiple inheritance in C++ so that we go for Interface in Java,which solve that problem.

As a Java programmer learning Python, what should I look out for? [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 9 years ago.
Improve this question
Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. I don't want to just program Java in Python. What are some things I should look out for?
A quick example - when looking through the Python tutorial, I came across the fact that defaulted mutable parameters of a function (such as a list) are persisted (remembered from call to call). This was counter-intuitive to me as a Java programmer and hard to get my head around. (See here and here if you don't understand the example.)
Someone also provided me with this list, which I found helpful, but short. Anyone have any other examples of how a Java programmer might tend to misuse Python...? Or things a Java programmer would falsely assume or have trouble understanding?
Edit: Ok, a brief overview of the reasons addressed by the article I linked to to prevent duplicates in the answers (as suggested by Bill the Lizard). (Please let me know if I make a mistake in phrasing, I've only just started with Python so I may not understand all the concepts fully. And a disclaimer - these are going to be very brief, so if you don't understand what it's getting at check out the link.)
A static method in Java does not translate to a Python classmethod
A switch statement in Java translates to a hash table in Python
Don't use XML
Getters and setters are evil (hey, I'm just quoting :) )
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python
(And if you find this question at all interesting, check out the link anyway. :) It's quite good.)
Don't put everything into classes. Python's built-in list and dictionaries will take you far.
Don't worry about keeping one class per module. Divide modules by purpose, not by class.
Use inheritance for behavior, not interfaces. Don't create an "Animal" class for "Dog" and "Cat" to inherit from, just so you can have a generic "make_sound" method.
Just do this:
class Dog(object):
def make_sound(self):
return "woof!"
class Cat(object):
def make_sound(self):
return "meow!"
class LolCat(object):
def make_sound(self):
return "i can has cheezburger?"
The referenced article has some good advice that can easily be misquoted and misunderstood. And some bad advice.
Leave Java behind. Start fresh. "do not trust your [Java-based] instincts". Saying things are "counter-intuitive" is a bad habit in any programming discipline. When learning a new language, start fresh, and drop your habits. Your intuition must be wrong.
Languages are different. Otherwise, they'd be the same language with different syntax, and there'd be simple translators. Because there are not simple translators, there's no simple mapping. That means that intuition is unhelpful and dangerous.
"A static method in Java does not translate to a Python classmethod." This kind of thing is really limited and unhelpful. Python has a staticmethod decorator. It also has a classmethod decorator, for which Java has no equivalent.
This point, BTW, also included the much more helpful advice on not needlessly wrapping everything in a class. "The idiomatic translation of a Java static method is usually a module-level function".
The Java switch statement in Java can be implemented several ways. First, and foremost, it's usually an if elif elif elif construct. The article is unhelpful in this respect. If you're absolutely sure this is too slow (and can prove it) you can use a Python dictionary as a slightly faster mapping from value to block of code. Blindly translating switch to dictionary (without thinking) is really bad advice.
Don't use XML. Doesn't make sense when taken out of context. In context it means don't rely on XML to add flexibility. Java relies on describing stuff in XML; WSDL files, for example, repeat information that's obvious from inspecting the code. Python relies on introspection instead of restating everything in XML.
But Python has excellent XML processing libraries. Several.
Getters and setters are not required in Python they way they're required in Java. First, you have better introspection in Python, so you don't need getters and setters to help make dynamic bean objects. (For that, you use collections.namedtuple).
However, you have the property decorator which will bundle getters (and setters) into an attribute-like construct. The point is that Python prefers naked attributes; when necessary, we can bundle getters and setters to appear as if there's a simple attribute.
Also, Python has descriptor classes if properties aren't sophisticated enough.
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python. Correct. Python uses optional arguments instead of method overloading.
The bullet point went on to talk about closure; that isn't as helpful as the simple advice to use default argument values wisely.
One thing you might be used to in Java that you won't find in Python is strict privacy. This is not so much something to look out for as it is something not to look for (I am embarrassed by how long I searched for a Python equivalent to 'private' when I started out!). Instead, Python has much more transparency and easier introspection than Java. This falls under what is sometimes described as the "we're all consenting adults here" philosophy. There are a few conventions and language mechanisms to help prevent accidental use of "unpublic" methods and so forth, but the whole mindset of information hiding is virtually absent in Python.
The biggest one I can think of is not understanding or not fully utilizing duck typing. In Java you're required to specify very explicit and detailed type information upfront. In Python typing is both dynamic and largely implicit. The philosophy is that you should be thinking about your program at a higher level than nominal types. For example, in Python, you don't use inheritance to model substitutability. Substitutability comes by default as a result of duck typing. Inheritance is only a programmer convenience for reusing implementation.
Similarly, the Pythonic idiom is "beg forgiveness, don't ask permission". Explicit typing is considered evil. Don't check whether a parameter is a certain type upfront. Just try to do whatever you need to do with the parameter. If it doesn't conform to the proper interface, it will throw a very clear exception and you will be able to find the problem very quickly. If someone passes a parameter of a type that was nominally unexpected but has the same interface as what you expected, then you've gained flexibility for free.
The most important thing, from a Java POV, is that it's perfectly ok to not make classes for everything. There are many situations where a procedural approach is simpler and shorter.
The next most important thing is that you will have to get over the notion that the type of an object controls what it may do; rather, the code controls what objects must be able to support at runtime (this is by virtue of duck-typing).
Oh, and use native lists and dicts (not customized descendants) as far as possible.
The way exceptions are treated in Python is different from
how they are treated in Java. While in Java the advice
is to use exceptions only for exceptional conditions this is not
so with Python.
In Python things like Iterator makes use of exception mechanism to signal that there are no more items.But such a design is not considered as good practice in Java.
As Alex Martelli puts in his book Python in a Nutshell
the exception mechanism with other languages (and applicable to Java)
is LBYL (Look Before You Leap) :
is to check in advance, before attempting an operation, for all circumstances that might make the operation invalid.
Where as with Python the approach is EAFP (it's easier to Ask for forgiveness than permission)
A corrollary to "Don't use classes for everything": callbacks.
The Java way for doing callbacks relies on passing objects that implement the callback interface (for example ActionListener with its actionPerformed() method). Nothing of this sort is necessary in Python, you can directly pass methods or even locally defined functions:
def handler():
print("click!")
button.onclick(handler)
Or even lambdas:
button.onclick(lambda: print("click!\n"))

How can I write code without "needing" comments for readability? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is it possible to write good and understandable code without any comments?
When coding often I hear that if comments are needed then it means that the code is too hard to understand. I agree that code should be readable but often the language itself makes the code hard to follow, because of "plumbing" and strange syntax. The languages I use most often are:
Java
Mootools
Ruby
Erlang
Any tips would be appreciated?
Thanks
Recommended reading: Clean Code by Robert C. Martin.
In brief, you should
use meaningful variable/method/class names,
keep your functions/methods short,
have each class and method do only one thing,
have the code in each method be on the same level of abstraction.
Don't fear of extracting even moderately complex expressions from if statements; which one is clearer to read, this
if (i >= 0 && (v.size() < u || d == e)) ...
or
if (foundNewLocalMaximum()) ...
(Don't try to find any meaning in the first code snippet, I just made it up :-)
Comments in clean code are almost never needed. The only exceptions I can think of is if you are using some obscure language feature (e.g. C++ template metaprogramming) or algorithm, and you give a reference to the source of the method/algorithm and its implementation details in a comment.
The main reason why any other kind of comments is not very useful in the long run is that code changes, and comments tend to not be updated alongside the changes in the corresponding code. So after a while the comment is not simply useless, but it is misleading: it tells you something (implementation notes, reasoning about design choices, bug fixes etc.) which refers to a version of the code which is long gone, and you have no idea whether it is relevant anymore for the current version of the code.
Another reason why I think that "why I chose this solution" is most often not worth documenting in the code, is that the brief version of such a comment would almost always be like either "because I think this is the best way", or a reference to e.g. "The C++ Programming Language, ch. 5.2.1", and the long version would be a three-page essay. I think that an experienced programmer most often sees and understands why the code is written like this without much explanation, and a beginner may not understand even the explanation itself - it's not worth trying to cover everyone.
Last but not least, IMO unit tests are almost always a better way of documentation than code comments: your unit tests do document your understanding, assumptions and reasoning about the code quite efficiently, moreover you are automatically reminded to keep them in sync with the code whenever you break them (well, provided you actually run them with your build...).
I don't think you can normally write code without comments.
Briefly, the code documents how. The comments document why.
I would expect the comments to indicate the conditions why the code has been written like that, limitations imposed by requirements or externalities, the impact that would result from changing the code, and other gotchas. The comments contain information that isn't contained within the code itself.
Comments along the code are supposed to tell you why you initially did something a certain way. It shouldn't mean the code is too hard to understand.
The most important things to follow are:
give your variables, methods, classes... meaningful names
write classes/ modules with a clean responsibility
don't mix up different levels of code (don't do bit shifting and high level logic inside of one method)
I think it is useful to write comments for USERS of your code - what the classes/methods/functions do, when an how to call it etc. In other words document the API.
If you need to comment how a method works for the benefit of maintainers then I think the code is probably too complex. In that case refactor it into simpler functions, as others have said.
I personally feel that having no comments at all is about as bad as having excessive commenting. You just need to find the right balance. About using long descriptive names for things this about sums it up for me: read this Also read Kernighan & Pike on long names.
You need to follow certain rules.
Give the entities (variable, classes, etc) readable and meaningful names.
Use design patterns extensively and name them accordingly, e.g. if it is a Factory name it FooFactory.
Have the code formatted properly, etc.

Besides dynamic typing, what makes Ruby "more flexible" than Java? [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
I've been using Java almost since it first came out but have over the last five years gotten burnt out with how complex it's become to get even the simplest things done. I'm starting to learn Ruby at the recommendation of my psychiatrist, uh, I mean my coworkers (younger, cooler coworkers - they use Macs!). Anyway, one of the things they keep repeating is that Ruby is a "flexible" language compared to older, more beaten-up languages like Java but I really have no idea what that means. Could someone explain what makes one language "more flexible" than another? Please. I kind of get the point about dynamic typing and can see how that could be of benefit for conciseness. And the Ruby syntax is, well, beautiful. What else? Is dynamic typing the main reason?
Dynamic typing doesn't come close to covering it. For one big example, Ruby makes metaprogramming easy in a lot of cases. In Java, metaprogramming is either painful or impossible.
For example, take Ruby's normal way of declaring properties:
class SoftDrink
attr_accessor :name, :sugar_content
end
# Now we can do...
can = SoftDrink.new
can.name = 'Coke' # Not a direct ivar access — calls can.name=('Coke')
can.sugar_content = 9001 # Ditto
This isn't some special language syntax — it's a method on the Module class, and it's easy to implement. Here's a sample implementation of attr_accessor:
class Module
def attr_accessor(*symbols)
symbols.each do |symbol|
define_method(symbol) {instance_variable_get "##{symbol}"}
define_method("#{symbol}=") {|val| instance_varible_set("##{symbol}", val)}
end
end
end
This kind of functionality allows you a lot of, yes, flexibility in how you express your programs.
A lot of what seem like language features (and which would be language features in most languages) are just normal methods in Ruby. For another example, here we dynamically load dependencies whose names we store in an array:
dependencies = %w(yaml haml hpricot sinatra couchfoo)
block_list %w(couchfoo) # Wait, we don't really want CouchDB!
dependencies.each {|mod| require mod unless block_list.include? mod}
It's also because it's a classless (in the Java sense) but totally object oriented (properties pattern) so you can call any method, even if not defined, and you still get a last chance to dynamically respond to the call, for example creating methods as necessarry on the fly. Also Ruby doesn't need compilation so you can update a running application easily if you wanted to. Also an object can suddenly inherit from another class/object at anytime during it's lifetime through mixins so it's another point of flexibility. Anyways I agree with the kids that this language called Ruby , which has actually been around as long as Java, is very flexible and great in many ways, but I still haven't been able to agree it's beatiful (syntax wise), C is more beatiful IMHO (I'm a sucker for brackets), but beauty is subjective, the other qualities of Ruby are objective
Blocks, closures, many things. I'm sure some much better answers will appear in the morning, but for one example here's some code I wrote ten minutes ago - I have an array of scheduled_collections, some of which have already happened, others which have been voided, canceled, etc. I want to return an array of only those that are pending. I'm not sure what the equivalent Java would be, but I imagine it's not this one-line method:
def get_all_pending
scheduled_collections.select{ |sc| sc.is_pending? }
end
A simpler example of the same thing is:
[0,1,2,3].select{|x| x > 1}
Which will produce [2,3]
Things I like
less code to get your point across
passing around code blocks (Proc, lambdas) is fun and can result in tinier code. e.g. [1, 2, 3].each{|x| puts "Next element #{x}"}
has the scripting roots of PERL.. very nice to slice n dice routine stuff like parsing files with regexps, et. all
the core data structure class API like Hash and Array is nicely done.
Metaprogramming (owing to its dynamic nature) - ability to create custom DSLs (e.g. Rails can be termed a DSL for WebApps written in Ruby)
the community that is spawning gems for just about anything.
Mixins. Altering a Ruby class to add new functionality is trivially easy.
Duck typing refers to the fact when types are considered equivalent by what methods them implement, not based on their declared type. To take a concrete example, many methods in Ruby take a IO-like object to operate on a stream. This means that the object has to implement enough functions to be able to pass as an IO type object (it has to sound enough like a duck).
In the end it means that you have to write less code than in Java to do the same thing. Everything is not great about dynamic languages, though. You more or less give up all of the compile-time typechecking that Java (and other strongly/statically typed languages) gives you. Ruby simply has no idea if you're about to pass the wrong object to a method; that will give you a runtime error. Also, it won't give you a runtime error until the code is actually called.
Just for laughs, a fairly nasty example of the flexibility of the language:
class Fixnum
def +(other)
self - other
end
end
puts 5 + 3
# => 2

Categories