- Design & Coding — top to bottom or bottom to top? [closed]
- 13 Answers 13
- How can I position my div at the bottom of its container?
- 24 Answers 24
- The flexbox approach!
- Pure CSS, Without Absolute positioning, Without Fixing any Height, Cross-Browser (IE9+)
- Filling UITableView with data from bottom to top
- Scrolling
- Rotating UITableView 180 degrees
- Flipping UITableView ’s Y axis
- Custom Bottom Sheet: как это должно работать
- Предисловие
- Кастомизация
- Изменение высоты
Design & Coding — top to bottom or bottom to top? [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago .
When coding, what in your experience is a better approach?
- Break the problem down into small enough pieces and then implement each piece.
- Break the problem down, but then implement using a top-down approach.
- Any other?
13 Answers 13
Here’s what I do:
Understand the domain first. Understand the problem to be solved. Make sure you and the customer (even if that customer is you!) are on the same page as to what problem is to be solved.
Then a high level solution is proposed to the problem and from that, the design will turn into bubbles or bullets on a page or whatever, but the point is that it will shake out into components that can be designed.
At that point, I write tests for the yet-to-be written classes and then flesh out the classes to pass those tests.
I use a test-first approach and build working, tested components. That is what works for me. When the component interfaces are known and the ‘rules’ are known for how they talk to each other and provide services to each other, then it becomes generally a straightforward ‘hook everything together’ exercise.
That’s how I do it, and it has worked well for me.
I tend to design top-down and implement bottom-up.
For implementation, building the smallest functional pieces and assembling them into the higher-level structures seems to be what works best for me. But, for design, I need to start from the overall picture and break it down to determine what those pieces will be.
You might want to look over the Agile Manifesto. Top down and bottom up are predicated on Built It All At Once design and construction.
The «Working software over comprehensive documentation» means the first thing you build is the smallest useful thing you can get running. Top? Bottom? Neither.
When I was younger, I worked on projects that were — by contract — strictly top down. This doesn’t work. Indeed, it can’t work. You get mountains of redundant design and code as a result. It was not a sound approach when applied mindlessly.
What I’ve noticed is that the Agile approach — small pieces that work — tends to break the problem down to parts that can be grasped all at once. The top-down/bottom-up no longer matters as much. Indeed, it may not matter at all.
Which leads do: «How do you decompose for Agile development?» The trick is to avoid creating A Big Thing that you must then decompose. If you analyze a problem, you find actors trying to accomplish use cases and failing because they don’t have all the information, or they don’t have it in time, or they can’t execute their decisions, or something like that.
Often, these aren’t Big Things that need decomposition. When they are, you need to work through the problem in the Goals Backward direction. From Goals to things that enable you to make that goal to things that enable the enablers, etc. Since goals are often Big Things, this tends to be Top Down — from general business goal to detailed business process and step.
At some point, we overview these various steps that lead to the goals. We’ve done the analysis part (breaking things down). Now comes the synthesis part: we reassemble what we have into things we can actually build. Synthesis is Bottom Up. However, let’s not get carried away. We have several points of view, each of which is different.
We have a model. This is often built from details into a larger conceptual model. Then, sometimes decomposed again into a model normalized for OLTP. Or decomposed into a star schema normalized for OLAP. Then we work back up to create a ORM mapping from the normalized model. Up — Down — Up.
We have processing. This is often built from summaries of the business processes down into details of processing steps. Then software is designed around the steps. Then the software is broken into classes and methods. Down — Up — Down.
[Digression. With enlightened users, this decomposition defines new job titles and ways of working. With unenlightened users, the old jobs stay and we write mountains of documentation to map old jobs onto new software.]
We have components. We often look at the pieces, look at what we know about available components, and do a kind of matching. This is the randomest process; it’s akin to the way crystals form — there are centers of nucleation and the design kind of solidifies around those centers. Web Services. Database. Transaction Management. Performance. Volume. Different features that somehow help us pick components that implement some or all of our solution. Often feels bottom-up (from feature to product), but sometimes top-down («I’m holding a hammer, call everything a nail» == use the RDBMS for everything.)
Eventually we have to code. This is bottom up. Kind of. You have to define a package structure. You have to define classes as a whole. That part was top down. You have to write methods within the classes. I often do this bottom-up — rough out the method, write a unit test, finish the method. Rough out the next method, write a unit test, finish the method.
The driving principle is Agile — build something that works. The details are all over the map — up, down, front, back, data, process, actor, subject area, business value.
How can I position my div at the bottom of its container?
Given the following HTML:
I would like #copyright to stick to the bottom of #container . Can I achieve this without using absolute positioning?
24 Answers 24
Assign position:relative to #container , and then position:absolute; bottom:0; to #copyright .
Actually, the accepted answer by @User will only work if the window is tall and the content is short. But if the content is tall and the window is short, it will put the copyright info over the page content, and then scrolling down to see the content will leave you with a floating copyright notice. That makes this solution useless for most pages (like this page, actually).
The most common way of doing this is the «CSS sticky footer» approach demonstrated, or a slightly slimmer variation. This approach works great — IF you have a fixed height footer.
If you need a variable height footer that will appear at the bottom of the window if the content is too short, and at the bottom of the content if the window is too short, what do you do?
Swallow your pride and use a table.
Try it out. This will work for any window size, for any amount of content, for any size footer, on every browser. even IE6.
If you’re cringing at the thought of using a table for layout, take a second to ask yourself why. CSS was supposed to make our lives easier — and it has, overall — but the fact is that even after all these years, it’s still a broken, counter-intuitive mess. It can’t solve every problem. It’s incomplete.
Tables aren’t cool, but at least for now, they are sometimes the best way to solve a design problem.
The flexbox approach!
In supported browsers, you can use the following:
The solution above is probably more flexible, however, here is an alternative solution:
As a side note, you may want to add vendor prefixes for additional support.
Yes you can do this without absolute positioning and without using table s (which screw with markup and such).
DEMO
This is tested to work on IE>7, chrome, FF & is a really easy thing to add to your existing layout.
It effectively does what float:bottom would, even accounting for the issue pointed out in @Rick Reilly’s answer!
Its an old question, but this is a unique approach that can help in several cases.
Pure CSS, Without Absolute positioning, Without Fixing any Height, Cross-Browser (IE9+)
Because normal flow is ‘top-to-bottom’ we can’t simply ask the #copyright div to stick to the bottom of his parent without absolutely positioning of some sort, But if we wanted the #copyright div to stick to the top of his parent, it will be very simple — because this is the normal flow way.
So we will use this in our advantage. we will change the order of the div s in the HTML, now the #copyright div is at the top, and the content follow it right away. we also make the content div stretch all the way (using pseudo elements and clearing techniques)
now it’s just a matter of inverting that order back in the view. that can be easily done with CSS transform.
We rotate the container by 180deg, and now: up-is-down. (and we inverse back the content to look normal again)
If we want to have a scroolbar within the content area, we need to apply a little bit more of CSS magic. as can be showed Here [in that example, the content is below a header — but its the same idea]
Filling UITableView with data from bottom to top
If you work on something like an chat app, you may need to use the UITableView in a way where data is filled from bottom to top. An example of this is a chat detail screen, where you want the UITableView to show the latest messages at the bottom when loaded, new messages are added to the bottom and immediately shown and older messages are loaded on top when the user scrolls to the top of the UITableView .
There are multiple ways to achieve this, each with some advantages and disadvantages.
Scrolling
The first simplest idea that comes to mind is using the UITableView as is and just scrolling it when necessary:
- Scroll to bottom when the initial messages are loaded
- Scroll to bottom when a new message is added
- When older messages are about to be added to the top, remember the position, add the older messages, scroll back to that position
The first two situations are easy to accomplish, but the last one is not. I could not find a way to make it works without a visible scrolling effect.
Rotating UITableView 180 degrees
Another solution is to rotate the UITableView by 180 degrees; rotating it upside down. Of course you have to also “flip” your data source but that is trivial to achieve. The advantage is that you do not have to do any scrolling when new messages are added to the bottom (which is the top of the rotated UITableView ) and if you use batch updates instead of reload neither when older messages are loaded.
After you rotate the UITableView
you have to also rotate all the cells
When you do this you immediately notice that the scrollbar is on the wrong side of the UITableView . You can fix this by setting
but this is not a very good solution. It depends on the width of the UITableView so you have to observe its changes and set it again with every change so the scrollbar is in the correct place when the user rotates the device and changes between portrait and landscape.
Also do not forget that the header becomes footer and vice versa.
Flipping UITableView ’s Y axis
The best solution I found is to flip the UITableView ’s Y axis. It gives you all the advantages of the previous solution, but you do not have to handle the scrollbar. It stays in the right place because only the content is flipped.
Custom Bottom Sheet: как это должно работать
Предисловие
Не так давно я прочитал статью о Bottom Sheet’e и, посовещавшись с коллегами, принял решение внедрить данную штуку в наше приложение. Потратив достаточно часов с целью научить Bottom Sheet выезжать в несколько шагов (like Google Maps), я осознал его тупость и ограниченность. Было найдено два решения: оборачивать всё в поток, который будет отслеживать состояние вытянутой шторки в реальном времени или же переписать некоторые методы класса BottomSheetBehavior (благо, лицензия Apache 2.0 позволяет это делать). Я выбрал второй вариант, ибо он показался мне более жизнеспособным, и сейчас, опираясь на свой опыт, я постараюсь поведать вам что из этого вышло. Надеюсь, что кому-то это пригодится. Что-ж, приступим.
Кастомизация
Я опускаю этапы создания проекта, добавление в него гугловского Bottom Sheet’a, ибо если вы читаете это, то всё вышеперечисленное уже преодолели. Нам понадобится перейти в класс BottomSheetBehavior и скопировать его содержимое в новый, нами созданный класс CustomBottomSheetBehavior. После того как скопировали, не забудьте переименовать всё, что отметится красным цветом. Также, в .xml файле нашего BottomSheet’a следует переименовать эту строку, ссылаясь на наш новый класс, должно получиться как-то так:
И так, мы имеем 700+ строк кода на Java, который выглядит страшно, что же с ними делать?
Для начала необходимо найти метод onViewReleased():
Нам понадобится изменить всего пару строк. Находим первый if <. >и заменяем его содержимое на этот код:
Теперь наш BottomSheet выдвигается в 2 этапа, останавливаясь посередине:
()
Изменение высоты
Но это ещё не всё, вы можете регулировать среднюю высоту. Для этого всё в том же классе найдите инициализацию переменной halfExpandedOffset:
При взгляде на эту строку становится понятно, что высоту мы можем настроить как нам угодно, даже в процентном соотношении. Лично я предпочёл изменить так:
()
Мой BottomSheet выдвигается на 40% от высоты основного View. На этом всё!