Why is it important to write the code in components/modules way? - modularization

Recently, I get to know that writing code in the modular or components way is important. But I am not sure why is it so important.
Can someone explain why is it important if you know?

code modularity is important for code readability, maintainability and post production support.
If you write a function which has 500 lines of code, it will be very difficult to understand but if you break your 500 lines of code into 10 different functions, it will be easy to understand and debug.
Example:
//without code modularity
public float performCalculation(float a, float b)
{
float result;
/** writing code calculation1**/
-
-
/** writing code calculation2**/
-
-
-
/** writing code calculating result**/
-
-
-
-
}
// with code modularity
public float performCalculation(float a, float b)
{
float calculation1 = performCalculation1(a,b); // call function performCalculation1
float calculation2 = performCalculation2(a,b); // call function performCalculation2
float result = findResult(calculation1 , calculation2 ); // call function findResult
return result;
}
Decide yourself which code is more readable. Here I have provided a very simple example but just think how will you maintain your code when it becomes huge.
Also, you can go through some online material to learn by yourself on best practices of code modularity.

Related

Greedy algorithm that works on two ends of an array in Haskell

I'm mostly curious about the general pattern that's best practice to implement algorithms where we we're marching along indices on opposite ends of an array.
Here's an example problem from leetcode.
Problem Statement
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example Solution
class Solution {
public:
int trap(int A[], int n) {
int left=0; int right=n-1;
int res=0;
int maxleft=0, maxright=0;
while(left<=right){
if(A[left]<=A[right]){
if(A[left]>=maxleft) maxleft=A[left];
else res+=maxleft-A[left];
left++;
}
else{
if(A[right]>=maxright) maxright= A[right];
else res+=maxright-A[right];
right--;
}
}
return res;
}
};
I've really enjoyed Haskell because of how elegant the solutions tend to be but I'm wondering if sometimes it's better to be able to fall back on imperative programming like is an option in OCaml

Parallelism; recursive or iterative?

I've been asked a very interesting question about threads and how to implement them, specifically recursive or iterative. This is in the context of sorting algorithms like quicksort.
When you have an array of elements that need sorting, would you rather implement a tree structure of threads(so recursive) that keep spawning new threads until the sorting size threshold is reached, or would you rather divide the array from the very beginning in even chunks and spawn threads for them?
Example recursive psuedocode:
void sort(int array[], int start, int end){
if(array.size > THRESHOLD){
//partition logic with calls to sort()
}
//sorting logic
}
Example iterative psuedocode:
void sort(int array[], int start, int end){
if(array.size > THRESHOLD){
int numberOfChunks = array.size / 1000;
for(int i = 0; i < numberOfChunks; i++){
//spawn thread for every chunk with calls to sort(), technically also recursion but only once and can be rewritten easily
}
}
//sorting logic
}
Assume the calls to sort are separate threads. I didn't want to clutter the examples with boilerplate. Try and look past the multitude of errors.
Picture:
What I've been taught in college for quicksort is to use the recursive method. But(and this is my opinion and nothing else) I think recursion has a tendency to make code unreadable and complex. Sure it looks fancy and works well, but it's harder to read.
What is the recommended way of doing things here?

Try to build a Java program to convert from Alloy instance to any language code

I am working on a research project that an Alloy generated instance holds entities (such as Signatures, Fields, Relations or Tuples) that resemble a programming language (such as java, c, etc).
For example, there are entities for Arithmetic operations (such as Add, Sub, Multiply, etc), for Relational operations (such equals, greater than, less than or equal, etc.) for variables, constants, and so on.
A tree view and graph view examples (max of two integers algorithm) of the model solution (instance found) are showing next. Those figures were extracted from Alloy Analyzer GUI.
My question is there a quick way to convert that alloy instance to any common language source code (Java would be the preferred language)?
Or should I do everything (Sigs, Fields, Atoms, language brackets, indentation, etc) by starting this way (going through an A4Solution) to build a kind of translator?
The main goal here is to build a Java program that is able to convert an Alloy instance to a Java source code file ready to compile and run.
//max of 2 integers' java source code at mymax2.java file
class MyMax2 {
public static void main(String[] args) {
int x;
int y;
int res;
if(y <= X) {
res = x;
} else {
res = y;
}
}
}
Finally, convert from XML to Java, by starting this way is not a desired option.
Thank you for help me on :)
Yours is really a formatted printing problem, with a tree as the data input. The tree is roughly an Abstract Syntax Tree (AST).
Do a post-order transversal of the tree, adding in the sensible text to each node as you travel back up the tree.
This means your "text for the node" function will look like a visitor, with lots of "policies" for each node type; however, there will be some wrinkles to address when it comes to variable scoping. Basically, the position of the declaration seems to be lost in your AST, and so you will have to write some code to cache the variable names in play, and define them in the upper blocks.
Since it might be ambiguous which block you would "unroll" your "variables to be declared" as you collapse your tree from the bottom up, your code will not be 100% identical to the input code. For example
public static void main(String[] args) {
int x;
if (x > 3) {
int y = 3 + x;
return x + y;
} else {
return 4;
}
}
might (after a full round trip of being converted to AST and back) read as
public static void main(String[] args) {
int x;
int y;
if (x > 3) {
y = 3 + x;
return x + y;
} else {
return 4;
}
}
Also, this assumes your AST has a pretty tight fit to the target programming language. For example, if you wanted to convert the presented AST to Prolog; you would quickly find out that the constructs in your AST are a poor fit for Prolog generation.
Should you need some direction, look into Pretty Printers which leverage most of the components of a compiler, with the exception that after they have their AST, they process it back out as source code.
There are a few wrinkles, but nothing too severe (provided your AST isn't missing a critical piece of information for the reverse back to source code).

Conventions to specifying digital fixed point binary numbers with macros

I was wondering if there an established convention to specifying fixed point binary numbers in decimal format (with the use of a macro). I am not sure if this possible in C/C++, but perhaps this is implemented in some language(s) and there is a notational standard like 0x000000,1.2f,1.2d,1l,etc
Take this example for instance:
I am using Q15.16 for instance, but would like to have the convenience of specifying numbers in decimal format, perhaps something like this:
var num:Int32=1.2fp;
Presumably, the easiest way with regards to Haxe macros, numbers can be initialized with a function:
#:macro
fp_from_float(1.2);
But it would be nice to have a shorthand notation.
Have you seen Luca's Fixed Point example with Haxe 3 and Abstracts?
It's here:
https://groups.google.com/forum/?fromgroups=#!topic/haxelang/JsiWvl-c0v4
Summing it up, with the new Haxe 3 abstract types, you can define a type that will be compiled as an Int:
abstract Fixed16(Int)
{
inline function new(x:Int) this = x;
}
You can also define "conversion functions", which will allow you to automatically convert a float into Fixed16:
#:from public static inline function fromf(x:Float) {
#if debug
if (x >= 32768.0 || x < -32768.0) throw "Conversion to Fixed16 will overflow";
#end
return new Fixed16(Std.int(x*65536.0));
}
The secret here is the #:from metadata. With this code, you will already be able to declare fixed types like this:
var x:Fixed16 = 1.2;
Luca's already defined some operators, to make working with them easier, like:
#:op(A+B) public inline static function add(f:Fixed16, g:Fixed16) {
#if debug
var fr:Float = f.raw();
var gr:Float = g.raw();
if (fr+gr >= 2147483648.0 || fr+gr < -2147483648.0) throw "Addition of Fixed16 values will overflow";
#end
return new Fixed16(f.raw()+g.raw());
}
Again, the secret here is in #:op(A+B) metadata, which will annotate that this function may be called when handling addition. The complete GIST code is available at https://gist.github.com/deltaluca/5413225 , and you can learn more about abstracts at http://haxe.org/manual/abstracts

some doubts in the following code

have a look at the code below once and help me out by clarifying my doubts.
I have commented my doubts on each lines where i have doubts. Moreover, its a part of code from a huge one. so please ignore the variable declarations and all.
The whole code is working perfect and no errors while compiled.
double Graph::Dijkstra( path_t& path )
{
int* paths = new int[_size];
double min = dijkstra(paths); // **is a function call or not? bcz i didn't found any function in the code**
if(min < 0) { delete[] paths; return -1;}
int i = _size - 1;
while(i>=0)
{
path.push(i); // **when will the program come out of this while loop, i'm wondering how does it breaks?**
i=paths[i];
}
path.push(0);
delete[] paths;
return min;
}
Full coding is available here.
double min = dijkstra(paths); // **is a function call or not? bcz i didn't found any function in the code**
It almost certainly is. However, it could be a free function, member function, function invoked by a macro, or something else. Without seeing the rest of the code, we can only guess.
while(i>=0)
{
path.push(i); // **when will the program come out of this while loop, i'm wondering how does it breaks?**
i=paths[i];
}
The program will come out of the loop as a soon as i is less than zero. If I had to guess, I'd say the each node in the path contains a link to the previous node's index with the last node in a path returning -1 or some other negative number.

Resources