Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Questions tagged [coding-style]

Coding style is a set of guidelines that helps readability and understanding of the source code.

12
votes
4answers
2k views

Which is the better way to call a method that is only available to one class that implements an interface but not the other one?

Basically I need to execute different actions given a certain condition. The existing code is written this way Base interface // DoSomething.java interface DoSomething { void letDoIt(String info)...
2
votes
2answers
192 views

What is wrong with writing web applications in a way that merges repository layer with view and with controller in the same file?

is there anything wrong with writing code in a way that merges view, repository, controller in the same file? i.e. global $db; // or $db = DBSingleton::get_db_instance(); // or global $container; $...
7
votes
4answers
260 views

Should I use assertions in a function that calls a function that have already them?

Let F(x) be a function that calls G(x), in which x must be greater than 0. If G already does assert(x > 0), should F do it as well?
1
vote
1answer
43 views

HashMap versus Object ? Which one is better to finally generate JSON output with KEY and VALUE

I do have this use case. callers(APIs in same microservice or different microservices) wants to report different KEYS and VALUES as an audit as part of their methods. There is a high possibilities ...
5
votes
1answer
311 views

Is there any reason *not* to forward declare all forward declarable function parameter/return types?

I ran into a situation where my build speeds have started to become large and have affected productivity. I had already minimized header dependencies before using forward declarations. Now I've ...
1
vote
3answers
210 views

What is a good method/practice I can employ to keep identical code snippits in two places in sync? Also, help documenting functionals

If I could get some input on the design of this, I would be grateful as well. Note that I'm programming in python. There's a function F that takes lots of data, runs some analysis on it (taking ...
3
votes
4answers
284 views

Is a constant name related to its current value an anti-pattern? [closed]

For example, suppose I have a string constant like this: const TITLEBAR_MESSAGE="Welcome back, %USERNAME%!"; I think it is more readable when it is named as const WELCOME_BACK_USERNAME="Welcome ...
1
vote
1answer
100 views

Are “I'm writing android applications” and “follow open-closed principles” reasons to allow global state?

For example, suppose I have an android application, in simple, there are 3 activities : MainActivity -> Main2Activity -> Main3Activity ,which user can visit them in sequence (eg: by button ...
3
votes
3answers
253 views

Structuring an if-else clause inside a for loop [closed]

Suppose I am doing an if-else clause inside a for loop. I like to structure it as for (...) if (...) // (part A) continue; //(part B) rather than for (...) if (...) ...
2
votes
2answers
121 views

How should I call splitted functions? centralize them? or call it one next to one?

According to Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?, I should split long functions into smaller functions even if they ...
4
votes
2answers
198 views

Should I define more methods to update necessary UI only, or less methods but update some UI unnecessarily?

For example, suppose my input data and UI is not in 1 to 1 relationship: html: <script> aChanged=function(){ }; bChanged=function(){ }; cChanged=function(){ }; </script> a:<input id=...
0
votes
0answers
95 views

How to handle error responses in a chain of CompletableFutures?

I have a long chain of completable futures in my project, with each step calling a backend API, which can give multiple error responses and one success response. Now, after parsing the response, I ...
0
votes
1answer
88 views

Chain function calls which return error codes or 0 on success in C [closed]

I used to call functions which returns int error code or 0 on success like this: int tmp = function_a() ?: function_b() ?: function_c(); if (tmp) handle_error(); Now I'm ...
42
votes
9answers
11k views

Is “avoid the yo-yo problem” a valid reason to allow the “primitive obsession”?

According to When is primitive obsession not a code smell?, I should create a ZipCode object to represent a zip code instead of a String object. However, in my experience, I prefer to see public ...
2
votes
1answer
126 views

Should I use complex expressions as function arguments?

I recently started working as a programmer and I am currently going through some codes (in C#) written by my colleagues. I have noticed that they tend to include logic within function calls within ...
1
vote
3answers
140 views

how to name two methods returning collection/single item

I want to have two methods, one which returns all items and another, which returns specific Item by name (assume Item has name field): Item getItem(String itemName) List<Item> getItems() How ...
1
vote
1answer
157 views

Should “Impl” naming always be avoided?

When implementing interfaces, as a general rule, Impl is evil. Ok, but is it evil in the following case? I've a service that has (and probably will have) only one implementation. In such case, ...
-1
votes
1answer
57 views

Storing average value in database or global scope?

I have a ratings web app where I want to output the average of all the ratings. How I'm currently doing it is recalculating the average every time a new review is posted and storing that in a database ...
1
vote
3answers
76 views

Class methods that are never called and everything handled by the internals of the class itself

I have a class in my code and I'm not sure if the design I've implemented is correct or if there is a better way to do it. The class I have created have important useful methods that is used by each ...
4
votes
5answers
485 views

Is copy and paste the head of for-loop (e.g.:for(let i=0;i<something.length;i++)) violating DRY principle?

For example, in my project, I often found some head of for-loop appears many times, eg: for(let i=0;i<SharedData.students.length;i++){ SharedData.students[i].something=..... } if(isReset){ ...
7
votes
1answer
275 views

Is it a good practice to create new variable to see the output of a function?

Consider these 2 types of implementation: public int add(int x, int y) { return mysteriousAdd(x, y); } public int add(int x, int y) { int output = mysteriousAdd(x, y); return output; } ...
3
votes
2answers
94 views

How thoroughly should you document business flows for a product or system you are learning?

I work on applications that have user documentation but it is not organized or updated to the current release. Is it worth my time to create my own documentation with screenshots and notes on all the ...
0
votes
1answer
146 views

Is Java-like restrictiveness OK Python style?

Good Pythonic style is much looser than Java's uptight restrictiveness: In Java, good style means private on methods wherever possible, all fields encapsulated, type declarations, defined ...
0
votes
2answers
305 views

Uncle Bob's clean architecture refactoring techniques for data objects / entities / LINQ queries

I have relatively simple controller logic with ugly parts of object creation. Some of the objects are really huge and even though all the controller does is to return the object, it looks messy and ...
3
votes
3answers
140 views

One try/catch for each error, or one global try catch and switch error?

I have multiple methods that could fail, let's say : readFile() parseFile() compute() Each of them could fail (e.g file not found, wrong file type, wrong data), should I put each of them in their ...
2
votes
3answers
172 views

Many simple ternary operator and one if-else, which one should I use?

For example, suppose I have a toggle button listener, and it has some tasks to do according to the state of toggle: style 1 : use many ternary operator: tutorialModeToggle(isTutorialOn){ ...
8
votes
2answers
176 views

fall-through switch for executing a sequence of steps

My program needs to execute a sequence of steps from start to end. But based on different input the start point will vary, e.g, some will run from the first step to end, some will run from the 2nd ...
1
vote
1answer
153 views

Using “On” at the start of a method name

From what I've observed, methods that start with the word "On" fall into two categories: A base class that defines an event will expose a protected method whose name starts with "On" followed by the ...
2
votes
1answer
89 views

How should I define hardcoded strings with some variable parts? Reuse more characters? Or keep the whole sentence?

for example, sometimes I need to define a hardcoded string with some variable parts, I often have trouble to choose the style: style 1 : reuse every characters when possible showMessage(num){ let ...
0
votes
3answers
98 views

Python - Proper way to call a function within a class based on a certain argument passed on

Let me illustrate with an example. Say I want to create a class Returns that generates the returns of a stock for example. Returns can be arithmetic or logarithmic, and I want to be able to choose at ...
1
vote
2answers
120 views

Why should imports be made at the beginning

Why is it considered good style to do all imports in a python application at the beginning, even if what is imported is used only once? I have been programming only shorter pieces of software for a ...
1
vote
1answer
66 views

Should I group all sound file definitions together? Or define some of them locally, if possible?

For example, suppose my application have some sound files, now I define all sound file references in a single class: public class SoundHelper{ public static Sound buttonSound=new Sound("(some url)...
3
votes
2answers
867 views

Is the meaning of `const` still thread-safe in C++11?

I recently came across Herb Sutter's video from about how the meaning of const and mutable has changed in C++11 to mean bitwise const (and thread-safe, as a consequence) instead of the traditional ...
1
vote
1answer
100 views

Making type conversions better readable

If you create a function, which should make the use of typeconversions more easy, but it maybe leads to more errors, would implement it globally, and what may speaks against it - when the readability ...
2
votes
2answers
346 views

Should I use Array or Set if both can be used to finish my task?

for example, Suppose I have a 2d array: let filterArr=[ [1,1,0,1,1], [0,1,1,1,0], [1,1,0,1,0] ]; I want to find and store the index of column that all are 1, i.e.:position 1 and 3, and the ...
2
votes
0answers
67 views

What're the necessary considerations when developing Cron Jobs (Scheduled Tasks)

I'm working on a website that has a section that shows the company's stock details and investor-related data. This data is retrieved through scheduled SOAP API calls. I created two scheduled tasks ...
0
votes
1answer
147 views

For arrays, should I use the first position to store the selected element, instead of variable like “selectedIndex”, if possible?

For example, I have a toggle button, which would show the current selected element, and would show next element when it is clicked, and it can loop back to first element. I have 2 ways to store the ...
3
votes
1answer
123 views

How hard should I try to write idiomatic code in a polyglot environment?

I work on a small team (2 primaries with one or two other occasional contributors) on a project/product that spans a number of separate platforms. We do embedded firmware in straight C on Arm0 chips. ...
2
votes
1answer
95 views

Should special case be inside or outside the for loop here?

For example, suppose I have 2 arrays: let arr1=[5,2,1]; let arr2=["abcde","ab","a"]; my work is simple : to check if length of strings in arr2 are larger than corresponding element with same index ...
3
votes
6answers
617 views

Is it better to write an efficient algorithm or code that is easier to understand?

So I was recently given a coding assignment from a large financial firm, and I thought of two ways to solve the problem. One of the ways involved 1 outer for loop and 1 inner for loop. In this case, ...
14
votes
6answers
2k views

Clean Code - Should I change the literal 1 to a constant?

To avoid magic numbers, we often hear that we should give a literal a meaningful name. Such as: //THIS CODE COMES FROM THE CLEAN CODE BOOK for (int j = 0; j < 34; j++) { s += (t[j] * 4) / 5; } ...
0
votes
3answers
195 views

PHP How can I get rid of redundant if statements

I have a bunch of if statements written in PHP for a project I'm working on. The pattern is that when the $price increases by 5 cents every time magazines are increased by 10. When the amount of ...
0
votes
2answers
127 views

Nomenclature for object inspection functionality

I'm adding mod support for a game I'm working on. I parse a data file that looks something like this: "requirements": { "is_class": { "class": "warrior" }, "is_in_faction": { "faction": "...
2
votes
2answers
120 views

Should I move tasks which is just for a specific element only out of for loop?

For example, I have a for loop, which element 0 has additional function to run compared with other elements, my question is, should the additional function be: 1.place inside for loop for(int i=0;i&...
17
votes
6answers
4k views

Foreach-loop with break/return vs. while-loop with explicit invariant and post-condition

This is the most popular way (it seems to me) of checking if a value is in an array: for (int x : array) { if (x == value) return true; } return false; However, in a book I’ve ...
4
votes
2answers
348 views

Why do I need a game loop with states, instead of init the next state in current state directly?

For example, it is common to see games with game loop and states: stateChanged(){ switch(state){ STATE.PLAYER_SELECT_CHARACTER: this.currentController=new PlayerSelectCharacterController()...
1
vote
2answers
236 views

If a instance method is used in one place only, should I move that method to that place?

For example, suppose I have a ZipCode class: public class ZipCode{ public value String value; public boolean validateFormat(){ ... } public otherMethod1(){ ... }...
3
votes
3answers
627 views

Is 2 methods calling each other code smell?

For example, if 2 classes depend on each other, it is a kind of circular dependency and should be avoided. How about methods? for example, if I have 2 methods which call each other: public void ...
3
votes
1answer
94 views

Should I replace a constant with static methods, if that constant usually 'cooperate' with a specific operator?

For example, to convert between g and kg, I have a constant 1000: public static final float G_TO_KG=1000; . . . this.result = someResult*1000; I found G_TO_KG always bind to operator '*'. So my ...
0
votes
2answers
259 views

Is it necessary for a boolean to be “false” by default?

For example, to store whether sound is on, I have a boolean originally named "isSoundOn": private boolean isSoundOn=true; however, the default value of boolean is false, but I want my application to ...