Why Dart Team does not follow their own style-guide? Or we all also must follow this guide? [closed] - anti-patterns

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
I cannot understand for whom Dart style-guide was written?
Dart Style Guide
Term PREFER form this guide:
"PREFER guidelines are practices that you should follow. However, there may be circumstances where it makes sense to do otherwise. Just make sure you understand the full implications of ignoring the guideline when you do"
Now one of the main practices that often discussed and, of course, we should follow it:
PREFER using var without a type annotation for local variables.
In short words, use type annotation in function body not recommended (except some very specific situations).
But when I look into source code of the Dart SDK I often see just the opposite.
Just one sample from many other similar.
runtime/lib/collection_patch.dart
Example:
void operator []=(K key, V value) {
int hashCode = key.hashCode;
List buckets = _buckets;
int length = buckets.length;
int index = hashCode & (length - 1);
_HashMapEntry entry = buckets[index];
while(entry != null) {
if (hashCode == entry.hashCode && entry.key == key) {
entry.value = value;
return;
}
entry = entry.next;
}
_addEntry(buckets, index, length, key, value, hashCode);
}
Why Dart team used type annotations for local variables instead of var?

I cannot understand for whom Dart style-guide was written?
It was written for Dart programmers. Why? Because..
As we build up an ecosystem of Dart code, it’s helpful if it follows a consistent coding style. A dedicated style guide for Dart helps us make the most of the features unique to the language and makes it easier for users to collaborate.
And it is up to each programmer or team whether or not to follow these guidelines, which are just a suggestion.

Related

Is Common Lisp static or dynamically typed? If both how is it done? [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 4 years ago.
Improve this question
I m doing a paper on python vs lisp in functional programming. I was seeing the typing system in Common Lisp. I have read that it is dynamic, lexical, strong. But my professor says it is static...can anyone clear this for me? its maddening!
According to the seminal paper on types by Luca Cardelli and Peter Wegner: On understanding types, data abstraction, and polymorphism, ACM Computing Surveys, 17(4):471-522, 1985,
Programming languages in which the type of every expression can be determined by static program analysis are said to be statically typed.
This is not true for Common Lisp. Consider, for instance, the following, legal, function definition:
(defun f(g x)
(funcall g x))
The type of the expression (funcall g x) inside the body of the function cannot be inferred or determined statically in any way.
In Common Lisp however you can, if you want, specify the types of the parameters of a function. For instance:
(defun f (g x)
(declare (type integer x)
(type (function (integer) float) g))
(funcall g x))
and in this case the compiler can infer that the type of (funcall g x) is float.
So, I think we could say that Common Lisp is not a statically typed language as normally intended, but it can be optionally used as such, if one provides appropriate type information.

Is String a valid Error type when it can be reported immediately in stdout? [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.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I recently implemented basic mechanics of a game of chess and used the Result<T, E> type for methods collecting human input, since it may be invalid. However, I'm not sure about what type I should pick for the possible error (E).
I have gathered that introducing new types is considered a good practice when building a library. However, when the Result can be handled immediately and the Err reported in stdout, isn't it simpler to just return Result<T, String>s or Result<T, &str>s (or Result<T, Cow<str>>s if both can occur)?
Consider the following case:
pub fn play() {
let mut game = Game::new();
loop {
match game.turn() {
Ok(()) => { game.turn += 1 }
Err(e) => println!("{}", e)
}
}
}
The game is played in the terminal and any input errors can immediately be reported. Is there any added value to introducing a custom error type in this case?
This is a rather broad question and there is no clear "right" or "wrong" answer.
It's important to note in your example, that strings carry very little easily accessible semantic information. Sure, you might be able to extract all semantic information by parsing the string, but this is really the wrong approach. Therefore, most bigger libraries or applications use error types that carry more semantic information to allow for easy error handling.
In your case, strings are probably fine, if you will print them immediately anyway. But there is a neat little trick in order to make at least the function signatures a bit more future proof: return Box<Error>.
The Error trait is a nice abstraction over errors. Pretty much every error type implements this trait. With the ? operator and the Into trait, it's possible to handle most errors with ease. Furthermore: there are a few type conversion impls for strings and Box<Error>. This allows to return strings as errors:
use std::error::Error;
fn foo() -> Result<(), Box<dyn Error>> {
std::fs::File::open("not-here")?; // io::Error
Err("oh noooo!")?; // &str
Err("I broke it :<".to_owned())?; // String
Err("nop".into())
}
fn main() {
println!("{}", foo().unwrap_err());
}
See the working demo.
Edit: please note, that Box<Error> carries less semantic information than another concrete error type like io::Error. So it's not a good idea to always return Box<Error>! It's just a better approach in your situation :)
Edit 2: I've read a lot on error handling models recently, which changed my opinion a bit. I still think this answer is pretty much true. However, I think it's by far not as easy as I formulated it here. So just keep in mind that this answer doesn't suit as general guide at all!

OO paradigm and encapsulated instance variables in Perl5 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need a way to make really encapsulated variables in Perl, without using any frameworks like Moose, so that you can access the instance variables only through getters and setters. There should be private instance variables.
The subroutines respectively methods are not a problem, because you can define them so that they can be used just through an instance respectively a reference. But variables you can always access via the package name, like class-vars.
Is there any way to prevent that?
It sounds like you're trying to prevent people from accessing the instance variables other than through the accessors; is that right?
Perl is a language for polite people, and the way you stop programmers from doing things you don't want them to do is to ask them not to. Yes, there are hacks, and the most obvious one here would be to make each object a closure (here's an article about it from the Perl Journal) but there are almost always ways around them, so you won't be able to stop the determined impertinent hacker
One of Larry Wall's excellent attributions is this, which explains my point superbly
Perl doesn't have an infatuation with enforced privacy. It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun
People tried to achieve this kind of thing with inside out objects. This presentation by David Golden explains it perfectly:
Inside-out objects first presented by Dutch Perl hacker Abigail in 2002
Spring 2002 – First mention at Amsterdam.pm,
June 28, 2002 – YAPC NA "Two alternative ways of doing OO"
July 1, 2002 – First mention on Perlmonks
Gained recent attention (notoriety?) as a recommended best practice with the publication of Damian Conway's Perl Best Practices
Despite their benefits, they bring significant complexity and are not universally welcomed
There are a number of modules that try to facilitate this type of programming.
I find them rather cumbersome, and they have since fallen out of favor.
You can also find them mentioned in perldoc perlobj:
In the past, the Perl community experimented with a technique called "inside-out objects". An inside-out object stores its data outside of the object's reference, indexed on a unique property of the object, such as its memory address, rather than in the object itself. This has the advantage of enforcing the encapsulation of object attributes, since their data is not stored in the object itself.
This technique was popular for a while (and was recommended in Damian Conway's Perl Best Practices), but never achieved universal adoption. The Object::InsideOut module on CPAN provides a comprehensive implementation of this technique, and you may see it or other inside-out modules in the wild.
To do really private variables you should use closures:
{
my $x;
sub get {
return $x;
}
sub set {
$x = shift;
}
}
set( 3 );
print get(); # prints 3
print $x; # ERROR
# Example with objects
package Class;
sub new {
bless {}, 'Class';
}
{
my $storage = {};
sub get {
$self = shift;
return $storage->{ "$self" };
}
sub set {
$self = shift;
$storage->{ "$self" } = shift;
}
}
package main;
print Class::x; #ERROR
$z = Class::new();
$z->set( 3 );
$y = Class::new();
$y->set( 5 );
print $y->get(); # 5
print $z->get(); # 3
The $x is local to the block. None except set and get may access it.
"$self" will be like "Class=HASH(0x1cf9160)". Because of each object has its own address in memory "$self" will never collision.
But actually you are not required to do so in other case that will be a stick in your wheel

When is it appropriate to use variable arguments in an Objective-C method? [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 9 years ago.
Improve this question
When is it appropriate to write a method with a variable number of arguments (like NSString's +stringWithFormat:)?
A brief search of variadic methods from Apple seems to include only two classes: when creating a data structure (NSArray's +arrayWithObjects:, NSSet's +setWithObjects:), or when formatting a string (NSString's +stringWithFormat:, NSPredicate's +predicateWithFormat:).
Apple's documentation for variadic methods includes an example that is subtly different from the previously mentioned data structure methods, but still in the same camp.
Is it appropriate to use variadic methods in any other context? Does Apple?
When is it appropriate to write a method with a variable number of arguments (like NSString's +stringWithFormat:)?
This method uses a printf-like attribute which checks the format string against the additional parameters. You should always add an attribute to your methods/functions when using a format string.
A brief search of variadic methods from Apple seems to include only two classes: when creating a data structure (NSArray's +arrayWithObjects:, NSSet's +setWithObjects:), or when formatting a string (NSString's +stringWithFormat:, NSPredicate's +predicateWithFormat:).
This form uses a nil sentinel. It's actually a bit relaxed because an unexpected nil can silently truncate your parameters without error or warning. As an example, the (new-ish) Objective-C Literals do not use this form; they use implementations which also take count as a parameter, and it is an error to pass nil elements.
Is it appropriate to use variadic methods in any other context?
It's used in many places in C, and there are also variadic macros. Generally, you should look for alternatives because variadics are a less safe API.
One place I will use them is if I need to wrap an API. In that case, I only forward the parameters to the API which takes the va_list.
You can find safer alternatives for almost every use case, especially since the introduction of blocks.
To my knowledge, Cocoa's uses of functions with variable number of arguments is limited to the two categories that you have mentioned. For example, NSLog and NSAssert can be considered functions from the second category, because it formats a string.
However, functions with variable number of arguments can be very useful when in other situations.
For example, you can define an API for evaluating expressions that looks like this:
NSNumber *res = [Evaluator evalExpression:#"%1 + %2 * %3", #10, #20, #5];
// returns #110
Another example could be an API for composing XML, like this:
MyXmlTree *tree = [MyXmlTree addElementWithTag:#"root" andChildren:
[MyXmlTree elementWithTag:#"hello"]
, [MyXmlTree elementWithTag:#"world"]
, nil];
The second example is a more complex case of composing a data structure (i.e. composing a tree, rather than defining a linear structure).

Ada: packaging concepts [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
This is a follow up of my earlier post here:
Ada: Understanding private types and understanding packaging
An implementation for the Rectangular type was made using one implementation i.e. Rectangular_Method_1 and a specification file and a body file were required for this implementation.
If we want to have another implementation Rectangular_Method_2 available to the user then the main file rectangular_Form.ads can be changed to
-- with Rectangular_Method_1;
-- package Rectangular_Form renames Rectangular_Method_1;
with Rectangular_Method_2;
package Rectangular_Form renames Rectangular_Method_2;
Questions
Is this the right way in software engineering to allow for another implementation in that the test file test_rectangular_form.adb remains the same for a different implementation?
If we create a second implementation Rectangular_Method_2, Is there a need to create a separate specification file in addition to the compulsory new body for this new implementation? There is the need however to provide the same procedures/functions for Vector_Basis_r, Set_Horz, Get_Horz etc in the new implementation so that we can call them in test_rectangular_form.adb.
Thanks...
If you use GNAT, you can use GPR files for the project. In there you can change the filename for specific packages, for example:
for Specification (Rectangular_Form) use "Rectangular_Method_1.ads";
for Implementation (Rectangular_Form) use "Rectangular_Method_1.adb";
you can even set this depending on an environment variable.
If your spec files all should look the same, you can use a Rectangular_Form.ads and only use the Implementation line from above.
An example GPR file could look like this:
project Example is
type Methods is ("normal", "something_else");
Method : Methods := external ("METHOD", "normal");
package Naming is
case Method is
when "normal" =>
for Implementation ("Example") use "example_normal.adb";
when "something_else" =>
for Implementation ("Example") use "example_something.adb";
end case;
end Naming;
end Example;
Then, you can use gnatmake -P example.gpr to compile it depending on your METHOD variable, or using a -XMETHOD=... parameter for gnatmake or just use the provided default value.
The example_*.adb should all contain the body of the package Example, not Example_Normal, etc..
Another way to do this would be to use tagged types.
package Rectangular is
type Instance is abstract tagged private;
procedure Vector_Basis_r (A : in Long_Float; D : out Instance);
procedure Set_Horz (R : in out Instance; H : Long_Float);
function Get_Horz (R : Instance) return Long_Float;
private
type instance is tagged null record;
end Rectangular;
with Rectangular;
package Rectangular_Method_1 is
type Instance is new Rectangular.Instance with private;
...
private
type Instance is new Rectangular.Instance with
record
Horz, Vert: Long_Float;
end record;
end Rectangular_Method_1;
(similar implementation for Rectangular_Method_2).
Then I believe you can write your code that uses it this way:
with Rectangular_Method_1;
with Rectangular_Method_2;
...
-- My_Rectangle : Rectangular_Method_1.Instance;
My_Rectangle : Rectangular_Method_2.Instance;
My_Rectangle.Set_Horiz(Whatever_Value);
...
In other words, all you'd have to change when switching between the two is the type names. Your client could even get rid of those changes by using a single subtype at the top.
subtype Rectangle_Instance is Rectangular_Method_2.Instance;
This would also give you the ability to move common code/fields up into the base class (package), which I think is sort of what you were after.